Nullity Policy: Not allow nullptr, prefer to use reference. preferreference than pointer See effective STL item 7 and 33.
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)
Composition: Ownership, same life time, not change in the middle.
Car and engine
Aggregation: Ownership, maybe same life time, maybe change in
the middle, People and toothbrush(same life time, changeable)
Teacher and student( not life time, changeable), Container and
pointer(same life time, changeable).
Associate: No Ownership, Includes as a member, different life
time, person and father(Not Nullity), person and wife( Nullity)
Dependency: No Ownership, Not Includes as a member, person
and friend.
OOP example1: If it’s mother-son(Composition) relationship, and it’s
compiler-given(not dynamic), just use member obj. Pay attention, If Engine
has no default ctor, you have to use initialization list in car ctor.
initialization list can be used to call base ctor.
OOP example2: If it’s Aggregation relationship, If has same life time, use
uniqu_ptr. But if has different life time, just use raw pointer or share_ptr.
TootuBrush example, use unique_ptr.
OOP example3: if it’s wife-husband(Association) relationship, If not
Nullity, use reference, such as mother, ou need to use initialization
list to init mother. If Nullity, such as wife, just use raw pointer.
Because no ownership involved, don’t use uniqu_ptr at all.
OOP example5: Suppose Man and Computer is has-a relationship and same
life time. Don’t use pointer or reference, just copy from a common computer,
and maybe later you can customize your computer, and it will not effect
common one. We can copy from commonComputer and init all Worker
object. And this time use initialization list can improve efficiency.
OOP example6: Change a semantic, unit1 may have a bus, but ownerpolicy tell us that bus can be shared by different unit. and life timepolicy tell us that bus and unit has separate life time. so here, we should
use shared_ptr