Weak pointer
std::weak_ptr<T> observes an object owned by shared_ptr without keeping it alive. lock() tries to promote to a shared_ptr; if the object is already gone, you get an empty shared_ptr.
Detailed Explanation
A cache should not keep every object in memory just because the cache has a pointer. A parent/child pair should not form a shared_ptr cycle. weak_ptr is the non-owning handle that still knows whether the object is alive.
You construct a weak_ptr from a shared_ptr. Copying a weak_ptr increments the weak count on the control block, not the strong count. The object is destroyed when the strong count hits zero. The control block lives until the weak count hits zero too. After the object dies, existing weak_ptrs become expired.
expired() is true if there is no owning shared_ptr left. lock() is the atomic "if not expired, increment strong count and return a shared_ptr". Use lock(), not expired() then lock(), if another thread might drop the last owner between the two calls.
You cannot dereference a weak_ptr. There is no operator*. That is the feature: you cannot forget it is maybe gone.
use_count() on a weak pointer is the strong count, for debugging.
enable_shared_from_this<T> lets an object that is already owned by a shared_ptr produce more shared_ptrs to itself (shared_from_this()). The weak pointer inside enable_shared_from_this is how it finds the control block. Calling shared_from_this() on an object that was not created via make_shared / shared_ptr throws (C++17) or is UB (C++11).
Do not use weak_ptr as a general "optional pointer". For a non-owning pointer that is guaranteed to be valid (the owner is on the stack above you), T* is enough and cheaper. weak_ptr is for optional liveness of a shared object.
Code Examples
#include <iostream>
#include <memory>
int main() {
std::weak_ptr<int> w;
{
auto s = std::make_shared<int>(7);
w = s;
if (auto locked = w.lock()) {
std::cout << *locked << '\n'; // prints: 7
}
}
std::cout << std::boolalpha << w.expired() << '\n'; // prints: true
}#include <memory>
#include <vector>
struct Node : std::enable_shared_from_this<Node> {
std::weak_ptr<Node> parent;
std::vector<std::shared_ptr<Node>> children;
std::shared_ptr<Node> self() { return shared_from_this(); }
};
int main() {
auto root = std::make_shared<Node>();
auto child = std::make_shared<Node>();
child->parent = root; // weak: no cycle
root->children.push_back(child);
}Common Gotchas
`shared_from_this` on a stack `Node`
there is no control block. Create the object with `make_shared`.
`expired()` then `lock()` is racy
another thread can drop the last owner in between. Just `lock()`.
Expired weaks keep the control block
a huge `make_shared` object plus leftover weaks still occupies the allocation after destruction of `T`.
Caching `lock()` results
a long-lived `shared_ptr` you kept from `lock()` is ownership again. That may be what you want; it is not "weak" anymore.