When all pointers and references to an object go out of scope, the object gets automatically destroyed. An ordinary pointer can be converted to a weak pointer. When all ordinary pointers and and references go out of scope, the object gets destroyed even if there's a weak pointer to the object:
#include <x/obj.H> #include <x/ref.H> #include <x/weakptr.H> class widgetObj : virtual public x::obj { // ... }; typedef x::ref<widgetObj> widget; typedef x::ptr<widgetObj> widgetptr; typedef x::weakptr<widgetptr> weakwidget; // ... widget w{widget::create()}; // ... weakwidget weakw=w.weaken(); // ... widgetptr origw=weakw.getptr(); if (!origw.null()) { // ... }
weaken
() creates a
weakptr
,
a weak pointer.
Alternatively, its constructor can be invoked directly, but note that
the template's constructor
takes a x::ptr
and not an x::ref
, but both x::ptr
s and x::ref
s have
a weaken
() method.
The only method implemented by a
weakptr
is getptr
(),
which returns an ordinary, strong pointer to the underlying object,
if it still exists.
If all other existing references to the object previously went out of
scope and the object got destroyed,
getptr
() returns an unbound reference.
Like x::ptr
, the
implementation of weakptr
is thread-safe, however see
important comments about thread safety of
references.
x::mpweakptr
implements a mutext-protected wrapper for weak pointers. It is a
reference-counted object that contains a mutex-protected weak pointer.
The thread-safe getptr
() method uses a mutex
to protect the call to the underlying weak pointer's
getptr
(). The similarly thread-safe
setptr
() method updates the mutex-protected
weak pointer.