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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With