Hi,
Is there an QVector replacement for explicit sharing?
Currently I am using QVector<float>, but it calls detach() when data() is called. If there a way not to call detach()? In another word, I need explicit sharing QVector.
Thanks
Printable View
Hi,
Is there an QVector replacement for explicit sharing?
Currently I am using QVector<float>, but it calls detach() when data() is called. If there a way not to call detach()? In another word, I need explicit sharing QVector.
Thanks
There is no such replacement. You can only pass references to the vector instead of copies of it everywhere.
I have to pass value of QVector<float>, at the same time I want to change value in one vector and all others get the same change.
Currently I do like this:
const float* data = vector.constData(); // <- doesn't call detach()
((float*)data)[ 3 ] = 5.6; // <- hard cast...
I know this is a very bad idea, but it is the only way not to call detach() and prevent copy on the write...
Any better idea?
Why not using shared pointers, from boost or some other lib?
I end up creating my own shared array using QVector
Code:
template <typename Type> class QfwSharedArray { public: QfwSharedArray() : d( new QfwSharedArrayData ) { } QfwSharedArray( const QVector<Type>& array ) : d( new QfwSharedArrayData ) { setArray( array ); } QfwSharedArray( const QfwSharedArray& org ) : d( org.d ) { } ~QfwSharedArray() { } QfwSharedArray& operator=( const QfwSharedArray& rhs ) { d = rhs.d; return *this; } bool operator==( const QfwSharedArray& rhs ) const { return d == rhs.d; } bool operator!=( const QfwSharedArray& rhs ) const { return !operator==( rhs ); } const QVector<Type>& array() const { return d->array; } QVector<Type>& array() { return d->array; } int size() const { return d->array.size(); } void resize( int size ) { d->array.resize( size ); } void setArray( const QVector<Type>& array ) { d->array = array; } operator QVector<Type>&() { return d->array; } operator const QVector<Type>&() const { return d->array; } QVector<Type>& operator() () { return d->array; } const QVector<Type>& operator() () const { return d->array; } Type &operator[]( int i ) { return d->array[ i ]; } const Type &operator[]( int i ) const { return d->array[ i ]; } private: public: QVector<Type> array; }; QExplicitlySharedDataPointer<QfwSharedArrayData> d; }; template <typename Type> QDebug operator<<( QDebug dbg, const QfwSharedArray<Type>& sa ) { dbg.nospace() << sa.array(); return dbg.nospace(); }