View Full Version : Implicit vs. explicit
lni
20th September 2009, 05:38
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
wysota
20th September 2009, 06:59
There is no such replacement. You can only pass references to the vector instead of copies of it everywhere.
lni
20th September 2009, 21:24
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?
scascio
21st September 2009, 08:50
Why not using shared pointers, from boost or some other lib?
lni
22nd September 2009, 02:26
I end up creating my own shared array using QVector
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:
class QfwSharedArrayData : public QSharedData {
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();
}
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.