CopperSpice API  1.7.2
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
 

Friends

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>
{
public:
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
{
CS_OBJECT(ScriptInterface)
public:
// Some other code unrelated to scripts that expects a QSharedPointer<Y>
CS_SLOT_1(Public, void slotCalledByScript(Y *managedBySharedPointer)
{ QSharedPointer<Y> yPtr = managedBySharedPointer->sharedFromThis(); } )
CS_SLOT_2(slotCalledByScript)
};

Method Documentation

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

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
inline

The const version of sharedFromThis().