PDA

View Full Version : QVector copy constructor



Caius Aérobus
3rd March 2008, 16:23
Hello,
I wonder why QList and QVector have a so different behaviour regarding compilation rules. Let us consider the following piece of code :



class T
{
public:
T(int i) {};
};
class C
{
public:
C() {};
QList<T> GetTs() {return QList<T>(this->Ts);};
private:
QList<T> Ts;
};


This code compiles well, but if I change it by replacing QList by QVector:



class T
{
public:
T(int i) {};
};
class C
{
public:
C() {};
QVector<T> GetTs() {return QVector<T>(this->Ts);};
private:
QVector<T> Ts;
};


I get a compilation error:


/Library/Frameworks/QtCore.framework/Versions/4/Headers/qvector.h: In member function ‘void QVector<T>::realloc(int, int) [with T = T]’:
/Library/Frameworks/QtCore.framework/Versions/4/Headers/qvector.h:297: instantiated from ‘void QVector<T>::detach_helper() [with T = T]’
/Library/Frameworks/QtCore.framework/Versions/4/Headers/qvector.h:104: instantiated from ‘QVector<T>::QVector(const QVector<T>&) [with T = T]’
error.cxx:10: instantiated from here
/Library/Frameworks/QtCore.framework/Versions/4/Headers/qvector.h:427: error: no matching function for call to ‘T::T()’
error.cxx:4: note: candidates are: T::T(int)
error.cxx:3: note: T::T(const T&)


The problem is due to the fact there exists no T::T() constructor and I can fix it by adding one:



class T
{
public:
T() {};
T(int i) {};
};
class C
{
public:
C() {};
QVector<T> GetTs() {return QVector<T>(this->Ts);};
private:
QVector<T> Ts;
};


which is not really nice since I would like to prevent users from instanciating class T without explicitely transmitting the integer parameter.
So could anybody help me fixing the problem:
- why QList and Qvector do not yield to identical compilation results?
- is there a better solution, assuming I would like that C::GetTs() returns a copy of table Ts in a very efficient way, which is the reason I would like to make the copy in this way, as explained in the Qt doc ("This operation takes constant time, because QVector is implicitly shared. This makes returning a QVector from a function very fast. If a shared instance is modified, it will be copied (copy-on-write), and that takes linear time.")?

jpn
3rd March 2008, 17:09
Are you sure you even need QVector? For most purposes, QList is the right class to use. Do you really need continuous memory?

Caius Aérobus
3rd March 2008, 17:39
Are you sure you even need QVector? For most purposes, QList is the right class to use. Do you really need continuous memory?

generally either I process every item in a for loop or I use direct accesses using indices, so I suppose it works quicker on continuous tables...

jpn
3rd March 2008, 17:52
I recommend reading Generic Containers (http://doc.trolltech.com/latest/containers.html) documentation. Pay special attention to "algorithmic complexity".