CopperSpice API  1.8.1
QThreadStorage< T > Class Template Reference

## Public Methods

bool hasLocalData () const

T & localData ()

localData () const

void setLocalData (T data)

## Detailed Description

### template<class T> class QThreadStorage< T >

The setLocalData() function stores a single thread-specific value for the calling thread. The data can be accessed later using localData().

The hasLocalData() function allows the programmer to determine if data has previously been set using the setLocalData() function. This is also useful for lazy initialization.

If T is a pointer type, QThreadStorage takes ownership of the data (which must be created on the heap with new) and deletes it when the thread exits, either normally or via termination.

For example, the following code uses QThreadStorage to store a single cache for each thread that calls the cacheObject() and removeFromCache() functions. The cache is automatically deleted when the calling thread exits.

void cacheObject(const QString &key, SomeClass *object)
{
caches.localData().insert(key, object);
}
void removeFromCache(const QString &key)
{
if (!caches.hasLocalData())
return;
caches.localData().remove(key);
}

### Caveats

• QThreadStorage can be used to store data for the main() thread. QThreadStorage deletes all data set for the main() thread when QApplication is destroyed, regardless of whether or not the main() thread has actually finished.

## Constructor & Destructor Documentation

template<class T >
inline

Constructs a new per-thread data storage object.

template<class T >
inline

Destroys the per-thread data storage object.

Note: The per-thread data stored is not deleted. Any data left in QThreadStorage is leaked. Make sure that all threads using QThreadStorage have exited before deleting the QThreadStorage.

hasLocalData()

## Method Documentation

template<class T >
 bool QThreadStorage< T >::hasLocalData ( ) const
inline

If T is a pointer type, returns true if the calling thread has non-zero data available. If T is a value type, returns whether the data has already been constructed by calling setLocalData or localData.

localData()
template<class T >
 T & QThreadStorage< T >::localData ( )
inline

Returns a reference to the data that was set by the calling thread. If no data has been set, this will create a default constructed instance of type T.

setLocalData(), hasLocalData()
template<class T >
 T QThreadStorage< T >::localData ( ) const
inline

Returns a copy of the data that was set by the calling thread.