CopperSpice API  1.7.4
QEnableSharedFromThis< T > Class Template Reference

Base class which provide a QSharedPointer for an existing object. More...

Public Methods

QSharedPointer< T > sharedFromThis ()
QSharedPointer< const T > sharedFromThis () const


template<class X >
class QSharedPointer

Detailed Description

template<class T>
class QEnableSharedFromThis< T >

A base class which allows obtaining a QSharedPointer for an object already managed by a shared pointer. You can inherit this class when you need to create a QSharedPointer from any instance of a class. For example, from within the object itself.

Returning QSharedPointer<T>(this) will not work because this creates multiple distinct QSharedPointer objects with separate reference counts. For this reason you must never create more than one QSharedPointer from the same raw pointer. QEnableSharedFromThis defines two member functions called sharedFromThis() that return a QSharedPointer<T> and QSharedPointer<const T>, depending on constness.

class Y: public QEnableSharedFromThis<Y>
return sharedFromThis();
int main() {
QSharedPointer<Y> p(new Y());
QSharedPointer<Y> y = p->f();
// p and y must share ownership
Q_ASSERT(p == y);

It is also possible to get a shared pointer from an object outside of the class itself. This is especially useful in code which provides an interface to scripts, where it is currently not possible to use shared pointers. For example:

class ScriptInterface : public QObject
// Some other code unrelated to scripts that expects a QSharedPointer<Y>
CS_SLOT_1(Public, void slotCalledByScript(Y *managedBySharedPointer)
{ QSharedPointer<Y> yPtr = managedBySharedPointer->sharedFromThis(); } )

Method Documentation

template<class T >
QSharedPointer< T > QEnableSharedFromThis< T >::sharedFromThis ( )

If this is being managed by a QSharedPointer, returns a shared pointer instance pointing to this otherwise returns a QSharedPointer holding a null pointer.

template<class T >
QSharedPointer< const T > QEnableSharedFromThis< T >::sharedFromThis ( ) const

The const version of sharedFromThis().