Purpose
Smart pointers, compared with raw pointers, have value semantics, which means we can freely create, copy and change it. However, consider the example:
Widget *p = new Widget();
You can not copy or assign this pointer at will because it will lead to memory leak.
std::unique_ptr
- A non-null std::unique_ptr always owns what it points to.
- Copying is not allowed but you can use move to transfer ownership to another pointer.
- Upon destruction, it destroys the resource.
- Same size of raw pointers
std::shared_ptr
- It can tell whether it is the last one pointing to a resource by consulting the resource’s reference count.
- Twice the size of raw pointers due to the use of reference count. Internally, shared_ptr contains a pointer to the resource and a pointer to the resource’s reference count.
std::weak_ptr
- Can not be dereferenced nor can they be tested for nullness
- Point to the same place as the std::shared_ptr initialize it, but they will not affect the reference count of the object they point to