You must ensure that there is only one manager object for each
managed object. You do this by writing your code so that when
an object is first created, it is immediately given to a shared_ptr
to manage, and any other shared_ptrs or weak_ptrs thatare needed to point to that object are all directly orindirectly copied or assigned from that first shared_ptr.
The customary way to ensure this is to write the new object
expression as the argument for a shared_ptr constructor, or use
the make_shared function template described below.
The exception to this immediate assignment rule is things like
factory methods that return a plain pointer to the object they
create – in this case however, the callee still should generally be
immediately assigning this returned object to a shared_ptr or
unique_ptr. Methods should return a plain-pointers when it is up
to the caller to handle ownership of the object(exclusive ownership
or shared ownership).
Methods can take plain-pointers as their arguments for just
observe it. Or use smart pointer to transfer or get ownership.
If you want to get the full benefit of smart pointers, your code should
avoid using raw pointers to refer to the same objects; otherwise it is
too easy to have problems with dangling pointers or double
deletions. In particular, smart pointers have a get() function that
returns the pointer member variable as a built-in pointer value.
This function is rarely needed. As much as possible, leave the
built-in pointers inside the smart pointers and use only the smart
pointers.
Three policy of smart pointer usage:
Owership policy: use smart pointer.
Observer Policy : use raw pointer, reference or weak_ptr
Nullity Policy: Not allow nullptr, prefer to use reference. preferreference than pointer
When you want to use raw pointer in STL container, There are two things
you need to consider:
Be wary of remove-like algorithms on containers of pointers.
"effective STL item 33"
When using containers of newed pointers, remember to delete the
pointers before the container is destroyed. "effective STL item 7".
All these two problems can be resolved by using smartpointer.
Observer pointer,observing pointers are pointers which do notkeep the pointed object alive raw pointers are bad when used for
performing manual memory management, i.e. new and delete. When
used purely as a means to achieve reference semantics and pass
around non-owning, observing pointers, there is nothing intrinsically
dangerous in raw pointers. Just not to dereference a dangling pointer
As a function return value. if you don’t want to create dynamically
or large array, don’t use new. Don’t use reference refer to a local
object created inside of fun.
If you have to use New, and you want to transfer Ownership from
callee to caller. You should use unique_ptr.
If there is no clear single owner, store and return shared_ptr.(in
this example, caller of fun() is single owner, so use unique_ptr)