6

Can somebody tell me, what is wrong with the following initialization of unique_ptr?

int main()
{
  unique_ptr<int> py(nullptr);
  py = new int;
  ....
}

g++ -O2 xxx.cc -lm -o xxx -std=c++11 says:

error: no match for ‘operator=’ (operand types are    ‘std::unique_ptr<int>’ and ‘int*’)
   py = new int;
      ^

Doing

unique_ptr<int> px(new int);

works just fine.

Anton Savin
  • 40,838
  • 8
  • 54
  • 90
Gerdos
  • 63
  • 1
  • 3

2 Answers2

10

The initialization is fine in both pieces of code, unique_ptr has constructors for both nullptr and naked pointers.

What is failing in the first snippet is the assignment, that is because unique_ptr does not have an operator= overload that accepts a naked pointer as its right hand side. It does accept another unique_ptr though, so you could do this:

py = unique_ptr<int>{new int};
py = std::make_unique<int>(); // Since c++14

Or you could look at reset that also accepts a naked pointer and has more or less the same meaning:

py.reset(new int);
KillianDS
  • 16,936
  • 4
  • 61
  • 70
7

Regarding

what is wrong with the following initialization of unique_ptr?

It's not the initialization that's problematic, it's the following assignment.

That's where the caret (up arrow) in the error message points: at the assignment. Strong hint: use the reset member function, or create a unique_ptr instance.


Regarding

doing

unique_ptr<int> px(new int);

just works fine.

It's the assignment, of a raw pointer to a unique_ptr, that's problematic, not the initialization.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331