Orxonox  0.0.5 Codename: Arcturus
Classes | Namespaces | Functions

Definition of WeakPtr<T>, wraps a pointer to an object. More...

#include "core/CorePrereqs.h"
#include <cassert>
#include "core/object/Destroyable.h"
#include "core/command/Functor.h"

Go to the source code of this file.

Classes

class  orxonox::WeakPtr< T >
 WeakPtr wraps a pointer to an object, which becomes nullptr if the object is deleted. More...
 

Namespaces

 orxonox
 Die Wagnis Klasse hat die folgenden Aufgaben:
 

Functions

template<class T , class U >
WeakPtr< T > orxonox::const_pointer_cast (const WeakPtr< U > &p)
 Uses a const_cast to cast a pointer of type U* to a pointer of type T* and returns it in a new WeakPtr<T>. More...
 
template<class T , class U >
WeakPtr< T > orxonox::dynamic_pointer_cast (const WeakPtr< U > &p)
 Uses a dynamic_cast to cast a pointer of type U* to a pointer of type T* and returns it in a new WeakPtr<T>. More...
 
template<class T , class U >
WeakPtr< T > orxonox::static_pointer_cast (const WeakPtr< U > &p)
 Uses a static_cast to cast a pointer of type U* to a pointer of type T* and returns it in a new WeakPtr<T>. More...
 
template<class T >
void orxonox::swap (WeakPtr< T > &a, WeakPtr< T > &b)
 Swaps the contents of two weak pointers. More...
 

Detailed Description

Definition of WeakPtr<T>, wraps a pointer to an object.

A WeakPtr wraps a pointer to an object. If the object gets deleted, the WeakPtr becomes nullptr. This can be used to store pointers to objects without knowing when they will be destroyed.

WeakPtr works only with objects that are derived from orxonox::Destroyable, because WeakPtr is intrusive and registers itself in the stored object, to get a notification if the object is being deleted.

Example:

MyClass* object = new MyClass(); // create an instance of MyClass
WeakPtr<MyClass> pointer = object; // create a WeakPtr and assign the object
if (pointer) // checks if pointer is not nullptr (which is true)
pointer->someFunction(); // calls MyClass::someFunction()
object->destroy(); // calls destroy() which deletes the object
if (pointer) // checks if pointer is not nullptr (which is now false)
pointer->someFunction(); // this will not be executed

In this example we assumed that MyClass is derived of Destroyable (otherwise it couldn't be used with a WeakPtr).

A callback can be registerd with the WeakPtr that will be called if the object gets deleted.

void myCallback() // definition of the callback function
{
orxout() << "Object destroyed" << endl;
}
MyClass* object = new MyClass(); // create an instance of MyClass
WeakPtr<MyClass> pointer = object; // create a WeakPtr and assign the object
pointer.setCallback(createFunctor(&myCallback)); // defines a callback
object->destroy(); // calls destroy() which deletes the object. prints "Object destroyed" to the console