Why unique_ptr
Is Better than auto_ptr
Consider the following statements:
auto_ptr<string> p1(new string("auto"); //#1auto_ptr<string> p2; //#2p2 = p1; //#3
When, in statement #3, p2
takes over ownership of the string
object, p1
is stripped of ownership. This, recall, is good because it prevents the destructors for both p1
and p2
from trying to delete the same object. But it also is bad if the program subsequently tries to use p1
because p1
no longer points to valid data.
Now consider the unique_ptr
equivalent:
unique_ptr<string> p3(new string("auto"); //#4unique_ptr<string> p4; //#5p4 = p3; //#6
In this case, the compiler does not allow ...
Get C++ Primer Plus now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.