C++: Difference between revisions

Line 227: Line 227:
[https://www.geeksforgeeks.org/auto_ptr-unique_ptr-shared_ptr-weak_ptr-2/ Smart Pointers]<br>
[https://www.geeksforgeeks.org/auto_ptr-unique_ptr-shared_ptr-weak_ptr-2/ Smart Pointers]<br>
Smart pointers were added in C++11.<br>
Smart pointers were added in C++11.<br>
There are 4 types of smart pointers:
There are 3 types of smart pointers:
* <code>auto_ptr</code> which is [https://stackoverflow.com/questions/3697686/why-is-auto-ptr-being-deprecated deprecated]
* <code>unique_ptr</code>
* <code>unique_ptr</code>
* <code>shared_ptr</code>
* <code>shared_ptr</code>
* <code>weak_ptr</code>
* <code>weak_ptr</code>
Use <code>unique_ptr</code> for ownership models.<br>
Use <code>unique_ptr</code> when one piece of code ''owns'' the memory at any given time.<br>
Use <code>shared_ptr</code> when multiple objects need to reference the same thing.<br>
Use <code>shared_ptr</code> when multiple objects need to reference the same thing.<br>
Use <code>weak_ptr</code> to avoid cyclic dependencies which cause issues with reference counting.<br>
Use <code>weak_ptr</code> to avoid cyclic dependencies which cause issues with reference counting.<br>
Line 252: Line 251:
auto my_car = std::make_unique<Car>();
auto my_car = std::make_unique<Car>();
</syntaxhighlight>
</syntaxhighlight>
;Notes
;Notes
* If the object you need is not very large, you can consider just including it as part of your class (or leaving it on the stack) rather than use pointers.
* If the object you need is not very large, you can consider just including it as part of your class (or leaving it on the stack) rather than use pointers.
Line 257: Line 257:
** Then you can call <code>shared_from_this()</code> from within any method (not the constructor).
** Then you can call <code>shared_from_this()</code> from within any method (not the constructor).
** May throw <code>bad_weak_ptr</code> if you call <code>shared_from_this()</code> without <code>make_shared</code> or if you do not publically inherit <code>std::enable_shared_from_this<T></code>
** May throw <code>bad_weak_ptr</code> if you call <code>shared_from_this()</code> without <code>make_shared</code> or if you do not publically inherit <code>std::enable_shared_from_this<T></code>
* When writing functions when do not operate on pointers and do not claim ownership of objects, you should just take a reference to the object as the argument.


====Garbage Collection====
====Garbage Collection====