Search code examples
c++smart-pointersraw-pointer

Is it considered bad practice to use a raw pointer in a constructor with the intention of wrapping it immediately in a smart pointer?


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 

};


Solution

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