This post will introduce two types of smart pointers, which can help programmers to manage objects allocated in heap.
unique_ptr
unique_ptr
can manage another object through a pointer and dispose of that object when the unique_ptr
goes out of scope. unique_ptr
ensure that there is only one smart pointer points to the object.
The object is disposed of using the assiciated deleter when either fo the following happens:
- the managing
unique_ptr
object is destoryed unique_ptr
object is assigned to another pointer viaoperator=
orreset()
The object can be disposed of using a user-supplied deleter by calling get_delter()(ptr)
.
unique_ptr
can manage a single object or a dynamically-allocated array of objects(allocated by new[]). For the latter, when the object is disposed, unique_ptr
will call delete[]
to distory the array of objects defautly.
|
|
get()
and release()
can return the raw pointer managed by unique_ptr
object.release()
will release the unique_ptr
object from responsibility of deleting the managed object, but get()
will not.
|
|
shared_ptr
shared_ptr
is a smart pointer that retains shared ownership of an object through a pointer. Several shared_ptr
object may own the same object. The object is destoryed when either of following happens:
- the last remaining
shared_ptr
owning the object is destoryed. - the last remaining
shared_ptr
owning the object is assigned another one viaoperator=
orreset()
.
A typical shared_ptr
holds two pointers:
- the stored pointer (return by
get()
). - a pointer to control block.
The control block pointers to a object that holds the number ofshared_ptr
who point to the managed object.
A poor sample for shared_ptr
implementation: