std::weak_ptr#include <memory> refers to an object owned by a std::shared_ptr#include <memory> without owning it, so it doesn't keep the object alive. It is available from the memory header:
#include <memory>
std::shared_ptr#include <memory><int> s = std::make_shared#include <memory><int>(5);
std::weak_ptr#include <memory><int> w = s;
s.use_count(); // 1, w is not an owner.A std::weak_ptr#include <memory> can't be used directly. lock() returns a std::shared_ptr#include <memory> to the object, or an empty one if the object has already been deleted:
if (std::shared_ptr#include <memory><int> p = w.lock()) {
*p; // 5
}
s.reset(); // Deletes the int, since s was the only owner.
w.lock(); // Empty std::shared_ptr#include <memory>.expired() checks whether the object has been deleted:
w.expired(); // trueThe main use of std::weak_ptr#include <memory> is breaking reference cycles. A parent owns its children with std::shared_ptr#include <memory>, and each child refers back to its parent with std::weak_ptr#include <memory>:
struct Node {
std::vector#include <vector><std::shared_ptr#include <memory><Node>> children;
std::weak_ptr#include <memory><Node> parent;
};
auto root = std::make_shared#include <memory><Node>();
auto child = std::make_shared#include <memory><Node>();
root->children.push_back(child);
child->parent = root;If parent were a std::shared_ptr#include <memory>, the root and child would keep each other alive and never be deleted.
Note
std::weak_ptr#include <memory> is also useful for caches and observers, which need to check whether an object still exists without keeping it alive.
Dan