auto foo = new Foo();
// ... stuff
delete foo
TL;DR: "raw" C++ memory management is hard.
We can use RAII to create "scoped" pointers
Only allows one managed "reference" to object
std::auto_ptr had weird copy semantics
... Compiles, but....
unique_ptr explicitly prevents you doing something like that...
Don't use auto-ptr, it's broken
unique_ptr is more useful, but still has obvious restrictions
VFPtrInterface
, which
contains a union consisting of atomicRefAndFlags_
or nonAtomicRefAndFlags_
Our SharedPtr is obviously a simplification, but it is conceptually similar to how std::shared_ptr works:
We can see the memory allocation for ourselves...
We can use std::make_shared to improve matters
Using make_shared, we get this:
What happens if a member function needs to pass "this" as a shared_ptr to some function/method?
note this requires that the type already has a shared pointer referring to it. (Our second call to Foo::m
is invalid)
shared_ptr
- works if and only if the object has not yet been deleted.
How does weak_ptr
keep track of things that have been deleted?
The control block holds a count of weak references as well as "actual" references
There's one extra weak reference for all the shared references.
When all the shared/strong references are gone away, we can delete the shared object and reclaim its memory
When all the weak references are gone away, we can eventually delete the control block
Beware make_shared and std::weak_ptr!
How might enable_shared_from_this be implemented?
Confused?
For shared ptrs, it makes sense if things are always destroyed the same way, regardless of who holds the last reference
We implement this by having a virtual function to do the work of destroying the object in the control block
We now have a reasonably complete picture of the content of std::shared_ptr
Why use a distinct pointer in the control block here?
namespace std {
template <typename T> class shared_ptr {
...
template <class Y>
shared_ptr (const shared_ptr<Y>& r, T* p)
noexcept;
...
};
}
Slides live at https://peadar.github.io/smartptrs
... and the source is here