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
};
make_unique()
copies a value, there should be no need for a pointer to be passed at all. The constructor ofA
can accept anint
, and then construct aunique_ptr
accordingly. – Peterint
were a superclass and the parametern
intended to be a subclass. – CiaranWelshmake_unique
supports that. – Peter