4

How do I create new and assign a value to a private unique_ptr in the constructor of a class? Tyvm :^) Keith

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);
kmiklas
  • 13,085
  • 22
  • 67
  • 103

1 Answers1

10

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • The first initializes the member variable which means it has the intended value in-place ready-to-go before the beginning of the user-supplied construction function. I tend to prefer this approach because it means avoiding an entire class of defects that come with uninitialized variables. On the other side, `std::make_unique` has advantages in memory layout, that shouldn't be dismissed either: https://stackoverflow.com/questions/22571202/differences-between-stdmake-unique-and-stdunique-ptr – Ben Jan 10 '17 at 00:58
  • Ignore the above comment about memory layout since it only applies to `shared_ptr`. Sutter has a nice GotW post on the general use of shared and unique pointers: https://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/ – Ben Jan 10 '17 at 01:07
  • You can use `std::make_unique()` in the constructor initialization list, eg: `A::A(int a) : int_ptr_( std::make_unique( a ) ) {}` – Remy Lebeau Jan 10 '17 at 01:18