0
votes

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 

};

1
Since make_unique() copies a value, there should be no need for a pointer to be passed at all. The constructor of A can accept an int, and then construct a unique_ptr accordingly.Peter
Yes, this is of course true in this simple example but I think I'm right in saying that this would cause object slicing to base class if int were a superclass and the parameter n intended to be a subclass.CiaranWelsh
In that case, pass the data to the constructor that is needed to construct the contained object (including selecting the right type if needed or, if the object is constructed using a factory idiom, the information needed by the factory). make_unique supports that.Peter
That strikes me as an odd way to do it. You may want to read Herb Sutter's guidance about smart pointer parameters.Eljay

1 Answers

2
votes

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)) {}
};