I want users not to have to create smart pointers to pass into object contructors themselves, but instead to pass in a raw pointer and then convert to a smart pointer within the initialisation. However, there are some warning bells ringing regarding creating memory leaks so I wanted to check: Is the following code problematic in any way?
#include <memory>
using namespace std;
class A {
private:
std::unique_ptr<int> num;
public:
explicit A(int* n){
num = std::make_unique<int>(*n);
}
};
int main(){
int n = 4;
A a(&n);
// A a(std::make_unique<A>(n)); // instead of having to do this, which is a moderately irritating
};
If you want to avoid smart pointer in interface, you might use by value or const reference:
class A {
private:
std::unique_ptr<int> num;
public:
explicit A(int n) : num(std::make_unique<int>(n)) {}
};