- Don’t use raw pointers as class members; that requires managing object life time and manually avoiding dangling pointers
- Use smart pointers instead of raw pointers
- Don’t use object references as class members as that makes objects of the class non-assignable (which means you cannot store said objects in standard C++ containers)
- Using raw pointers and object references to objects stored in standard C++ containers is problematic or impossible. Objects in containers can be relocated (addresses can change) rendering raw pointers and object references invalid.
- Best (only feasible?) option is to store std::shared_ptrof the dynamically allocated object in the container.
- std::shared_ptris reference counted- std::weak_ptris not
- Use std::make_sharedto create anstd::shared_ptrto a dynamically created object instance or usestd::shared_ptr(new T())
- Only way to access members via std::weak_ptris by callingstd::weak_ptr::lockwhich returns anstd::shared_ptror 0
- To create an std::weak_ptrfrom the this pointer, the class must first derive fromstd::enable_shared_from_thisand then call theshared_from_thisfunction to get anstd::shared_ptrpointing to the object. The object in question must be “owned” by anstd::shared_ptror else undefined behaviour results. Also,shared_from_thismust not be called from a constructor since the object is yet to be reference counted (i.e. object is not yet “owned” by anstd::shared_ptr)
- As a result of the previous point, it helps to ensure that objects can only be created via std::shared_ptrby using a public staticcreatefunction (which returns objects “owned” by anstd::shared_ptr) and making constructors private. Note that when constructors are made private, you can no longer use std::make_shared to create a shared pointer. You must usestd::shared_ptr(new T())in this case.
Modern C++ Object Relationships