5,321
edits
(→Memory) |
|||
Line 140: | Line 140: | ||
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> | ||
If you are using C++14 or newer, you should use <code>make_unique</code> or <code>make_shared</code> which will only make one memory allocation for both the object and the pointer rather than two memory allocations.<br> | |||
Alternatively if you already have a smart pointer, you can call <code>my_ptr.reset(new Car())</code> to change the pointer or <code>my_ptr.reset()</code> to deallocate the object referenced by the pointer. | |||
Example: | Example: | ||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> |