C++: Difference between revisions

 
Line 265: Line 265:
Smart pointers were added in C++11.<br>
Smart pointers were added in C++11.<br>
There are 3 types of smart pointers:
There are 3 types of smart pointers:
* [https://en.cppreference.com/w/cpp/memory/unique_ptr <code>unique_ptr</code>] - one piece of code ''owns'' the memory at any given time.<br>
* [https://en.cppreference.com/w/cpp/memory/unique_ptr <code>std::unique_ptr</code>] - one piece of code ''owns'' the memory at any given time.<br>
* <code>shared_ptr</code> - the memory has multiple owners.
* <code>std::shared_ptr</code> - the memory has multiple owners.
* <code>weak_ptr</code> - a non-owning reference to a shared_ptr.
* <code>std::weak_ptr</code> - a non-owning reference to a shared_ptr.


In general, there should be one object owning an object using a <code>unique_ptr</code>. Whenever you pass the value around, other functions should receive the object as a reference making it clear that they do not have ownership of the object. Smart pointers are nullable and assignable similar to regular pointers.
In general, there should be one object owning an object using a <code>unique_ptr</code>. Whenever you pass the value around, other functions should receive the object as a reference making it clear that they do not have ownership of the object. Smart pointers are nullable and assignable similar to regular pointers.