boost::openmethod::weak_virtual_ptr

Weak pointer to an object, remembering its v‐table pointer

Synopsis

Declared in <boost/openmethod/interop/std_weak_ptr.hpp>

template<
    class Class,
    class Registry = registry_affinity<Class>>
class weak_virtual_ptr;

Description

A weak_virtual_ptr tracks an object with a std::weak_ptr, and remembers its v‐table pointer. It is a storage facility, not a virtual_ptr: it cannot be dereferenced, compared, or used as a virtual parameter, because the object may no longer exist. It can be passed to a method as an ordinary parameter. Call lock() to obtain a shared_virtual_ptr, then use it as usual. Since the v‐table pointer is copied from the weak pointer, lock() costs no more than std::weak_ptr::lock(): no hash table lookup is needed.

Remembering the v‐table pointer is safe with respect to the lifetime of the object: a std::weak_ptr keeps the control block alive, so once the object is destroyed, the weak pointer stays expired, and the v‐table pointer can never be applied to another object.

As for any virtual_ptr, the remembered v‐table pointer is invalidated when boost::openmethod::initialize is called again, unless the registry uses policies::indirect_vptr.

Example

struct Animal {
    virtual ~Animal() = default;
};
struct Dog : Animal {};
struct Cat : Animal {};

BOOST_OPENMETHOD_CLASSES(Animal, Dog, Cat);

shared_virtual_ptr<Animal> animal = make_shared_virtual<Dog>();
weak_virtual_ptr<Animal> observer = animal;

std::cout << poke(observer.lock()) << "\n"; // bark

animal = nullptr;
std::cout << std::boolalpha << observer.expired() << "\n"; // true

Type Aliases

Name

Description

element_type

Class pointed to by the std::weak_ptr

Member Functions

Name

Description

weak_virtual_ptr [constructor]

Constructors

operator=

Assignment operators

lock

Lock the weak pointer

expired

Check whether the object still exists

use_count

Get the number of std::shared_ptr objects sharing the object

owner_before

owner_before overloads

reset

Release the reference to the object

swap

Swap with another weak_virtual_ptr

pointer

Get the weak pointer to the object

vptr

Get the v‐table pointer

Template Parameters

Name

Description

Class

The class of the object, possibly cv‐qualified

Registry

The registry in which Class is registered. Defaults to the registry Class has an affinity for, see registry_affinity.

See Also

Created with MrDocs