Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Definitive Guide to Shared vs Unique vs Weak Pointers | Advanced topics
C++ Smart Pointers
course content

Conteúdo do Curso

C++ Smart Pointers

C++ Smart Pointers

1. Introduction to Smart Pointers
2. Unique Pointers
3. Shared Pointers
4. Weak Pointers
5. References
6. Advanced topics

bookDefinitive 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.

Shared
Unique
Weak
Ownership semanticsAllows multiple pointers to share ownership of an objectExclusive ownership; only one pointer can own an objectNon-owning pointers; do not affect object lifespan
ConstructionCreated using std::make_shared or std::shared_ptrCreated using std::make_unique or std::unique_ptrNo direct construction; derived from shared pointers
SuitabilitySuitable for scenarios requiring shared ownershipIdeal for scenarios that need exclusive ownershipBreaks cyclic dependencies
Use casesShared 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 overheadHigher, due to reference counting for tracking ownershipLower than shared pointers as no reference counting involvedNegligible overhead; dependent on shared pointer usage
Performance impactHighest, due to reference countingLower, because no reference counting neededMinimal; just an observer
CopyabilityPossibleNot possiblePossible
AssignabilityAssignableNot assignableAssignable
Memory cleanupDeallocated when reference count reaches zeroAutomatically deallocated when the owning pointer goes out of scopeNo effect on object lifespan
Circular referencesPossibleNot possibleNot applicable
Exception safetySafeSafeSafe
Finish the course?

Finish the course?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 6. Capítulo 4
We're sorry to hear that something went wrong. What happened?
some-alt