std::shared_ptr
std::shared_ptr
is a C++ smart pointer who takes shared ownership of the pointee.
It solves some of the memory problems associated with the C language which are memory leaks; buffer overruns and dangling pointers. The first two can be solved by using std::vector
; the first and last one by using std::shared_ptr
. shared_ptr
has though some sharp edges:
-
one can create cycles between
std::shared_ptr
(i.e. A points to B; B points to A). The memory isn't released then. Solution is to usestd::weak_ptr
to break the cycle. Alternatively one can use a raw pointer to point back to the owner. - never assign a 'raw' resource to two
std::shared_ptr's
. Instead once a resource is assigned to astd::shared_ptr
use thestd::shared_ptr
to share that resource. -
use
enabled_shared_from_this
to hand out astd::shared_ptr
of yourself. This fails in constructor because thestd::shared_ptr
structure is build after the constructor returns.
Garbage collectors don't suffer from these issues but the runtime price one pays for it is large. Also their non-deterministic destruction may another big hurdle to coop with.