Contenido del Curso
C++ Smart Pointers
C++ Smart Pointers
Definitive Guide to Shared vs Unique vs Weak Pointers
In the last theoretical chapter of our course, we will reinforce all the learned concepts so far to create a comprehensive comparison table. This table will serve as a practical guide to help us select the most suitable smart pointer for various dynamic memory management needs.
Ownership semantics | Allows multiple pointers to share ownership of an object | Exclusive ownership; only one pointer can own an object | Non-owning pointers; do not affect object lifespan |
Construction | Created using std::make_shared or std::shared_ptr | Created using std::make_unique or std::unique_ptr | No direct construction; derived from shared pointers |
Suitability | Suitable for scenarios requiring shared ownership | Ideal for scenarios that need exclusive ownership | Breaks cyclic dependencies |
Use cases | Shared database resource; shared counter object etc. | A database resource owned exclusively by a class; a dynamic counter object exclusive to a class etc. | To represent weak nodes in a graph or linked list; to implement observer patterns |
Memory overhead | Higher, due to reference counting for tracking ownership | Lower than shared pointers as no reference counting involved | Negligible overhead; dependent on shared pointer usage |
Performance impact | Highest, due to reference counting | Lower, because no reference counting needed | Minimal; just an observer |
Copyability | Possible | Not possible | Possible |
Assignability | Assignable | Not assignable | Assignable |
Memory cleanup | Deallocated when reference count reaches zero | Automatically deallocated when the owning pointer goes out of scope | No effect on object lifespan |
Circular references | Possible | Not possible | Not applicable |
Exception safety | Safe | Safe | Safe |
¡Gracias por tus comentarios!