Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with this initialization of unique_ptr?

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.

like image 994
Gerdos Avatar asked Mar 04 '15 11:03

Gerdos


2 Answers

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);
like image 84
KillianDS Avatar answered Oct 03 '22 07:10

KillianDS


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.

like image 27
Cheers and hth. - Alf Avatar answered Oct 03 '22 05:10

Cheers and hth. - Alf