"Just remember to" is seldom the best solution! So we need smart
pointer to perform delete operator automatically.
When throw an exception, delete will not be invoked at all, It will
cause memory leaking.
In previous example codes, aupr is nullptr default. You avoid wild
pointer problem.
The idea of smart pointer is putting *p into a local pointer-like object, then
when it go out scope or unwind-stack when exception is thrown, It will call
destructor, then delete p.
There are three kinds of smart pointer: auto_ptr, unique_ptr, and
shared_ptr. But only unique_ptr and shared_ptr are recommended to use.
auto_ptr is now deprecated, and should not be used in new code. When you
get a chance, try doing a global search-and-replace of auto_ptr to
unique_ptr in your code base.
When you construct a smart pointer, you must use 1) a pointerand 2) this pointer must be produced by new. You can’t build inthis way unique_ptr<double> ptr(&df);
Why auto_ptr not recommended? 1) When you assign targetP = sourceP, it
will cause sourceP set to be NULL, It will cause trouble when you use
sourceP in the future. 2)You can’t create container includes auto_ptr,
compiler prohibit you doing so!
smart pointer is used mainly for ownership, It doesn’t support Inheritance
well. Don’t use smart pointer when you want to use in polymorphous
When in doubt, prefer unique_ptr by default, and you can always later
move-convert to shared_ptr if you need it. If you do know from the start
you need shared ownership, however, go directly to shared_ptr via
make_shared. If you compiler report error about unique_ptr, then you
should consider to use shared_ptr