c++c++11smart-pointersunique-ptr

How to create a new value and assign to a private unique_ptr in a class constructor?


How do I create new and assign a value to a private unique_ptr in the constructor of a class?

My best effort:

#include <iostream>
#include <memory>

class A {
public:
    A() {};
    A(int);
    void print();
private:
    std::unique_ptr<int> int_ptr_;
};
A::A(int a) {
    int_ptr_ = new int(a);
}
void A::print() {
    std::cout << *int_ptr_ << std::endl;
}
int main() {
    A a(10);
    a.print();
    std::cout << std::endl;
}

Compiler result:

smartPointer2.1.cpp:13:11: error: no match for ‘operator=’ (operand types are ‘std::unique_ptr<int>’ and ‘int*’)
  int_ptr_ = new int(a);

Solution

  • Write

    A::A(int a) : int_ptr_( new int(a) )
    {
    }
    

    Or you could write

    A::A(int a) 
    {
        int_ptr_.reset( new int(a) );
    }
    

    or

    A::A(int a) 
    {
        int_ptr_ = std::make_unique<int>( a );;
    }
    

    The first approach is better because in the other two apart from the default constructor there is called also an additional method or the move assignment operator.