Reputation: 9212
This is the code.
int main()
{
unique_ptr <int> p {nullptr};
int val = 100;
p = &val; // Not working - compilation error
p = move(&val); // Not working - compilation error
cout << *p;
return 0;
}
What is the correct way?
Upvotes: 0
Views: 153
Reputation: 42888
Only dynamically allocated objects should be assigned to unique_ptr
s, because the unique_ptr
may try to delete
the object.
As for the actual question, the reset()
function of unique_ptr
is used to reassign the pointer.
Upvotes: 3
Reputation: 437854
With unique_ptr::reset
:
p.reset(&val);
Of course in this particular case this will result in undefined behavior when p
goes out of scope and it tries to delete
the int, but that's another matter.
Upvotes: 1