CS247 Lecture 14
Last Time: Exception safety, RAII, Smart pointers This Time: Shared_ptrs, Decorator Pattern, Observer Pattern
What if we want shared ownership, where same memory is deleted only if all the pointers pointing to it are deleted?
We can achieve this via std::shared_ptr<T>
.
shared_ptr
maintains a reference count, which keeps track of how many shared pointers point at this memory. When it hits 0, memory is freed.
Shared Pointers are not perfect.
There are still problems with shared_ptr
s:
- Susceptible if you use the constructor
q
has no knowledge ofp
’s existence
Danger
The problem here is that you’re using the constructor of
std::shared_ptr
to initialize bothp
andq
with the same raw pointercp
. This means bothp
andq
think they own the same object. When bothp
andq
go out of scope, they will each try to delete the object, leading to a double delete and undefined behaviour.To avoid this issue, you should construct
std::shared_ptr
usingstd::make_shared
or by directly passing the constructor arguments:
- Cyclical reference issue
- If we have multiple shared pointers that point at each other, we have the issue that some pointers may never be deleted
myEdges
: Thisshared_ptr
points to a collection ofEdge
objects associated with the currentNode
. TheseEdge
objects might also contain references to otherNode
objects, creating a graph-like structure.neighbors
: Thisshared_ptr
points to otherNode
objects that are considered neighbors of the currentNode
. This establishes a connection between differentNode
instances in the graph.
full example through ChatGPTt:
In general, shared ownership is somewhat rare. Take care in constructing your programs. Usually, it suffices to use the following:
unique_ptr
or object field - ownership/Composition- raw pointer or reference - Aggregation/has-a
shared_ptr
- shared ownership
Exercise: Implement shared_ptr
CS247 final practice
We’ll come back to exception safety later.
- Provide some standard “good” solution to a common problem
- One common problem: adding / removing behaviour at run-time with a polymorphic class
- One example: Windowing system - GUI
If we attempt to make a class for each possible feature, for features, there are possible configurations. Combinatorial explosion!
Solution: Decorator Pattern (Linked List of functionalities)
Abstract Component - Gives the interface for our classes Concrete Component - Implements the “basic” version of the interface
Abstract Decorator - Organize decorators and has-a decorator or the concrete component.
Concrete Decorators - Implement the interface, call operation()
on the next object in this linked list.
ScrollBar Tabbing Basic Window
Example: Pizza
Next: CS247 Lecture 15