Hi all!
While I was looking at the code of qvector.h (the header file of QVector class - I use Qt 4.2.2) and I noticed something which I don't understand. For example, here is the implementation of the QVector:append() method:
template <typename T>
void QVector<T>::append(const T &t)
{
const T copy(t);
if (d->ref != 1 || d->size + 1 > d->alloc)
realloc(d->size, QVectorData::grow(sizeof(Data), d->size + 1, sizeof(T),
QTypeInfo<T>::isStatic));
if (QTypeInfo<T>::isComplex)
new (d->array + d->size) T(copy);
else
d->array[d->size] = copy;
++d->size;
}
template <typename T>
void QVector<T>::append(const T &t)
{
const T copy(t);
if (d->ref != 1 || d->size + 1 > d->alloc)
realloc(d->size, QVectorData::grow(sizeof(Data), d->size + 1, sizeof(T),
QTypeInfo<T>::isStatic));
if (QTypeInfo<T>::isComplex)
new (d->array + d->size) T(copy);
else
d->array[d->size] = copy;
++d->size;
}
To copy to clipboard, switch view to plain text mode
So my question is:
What's the use of the copy variable? Is it there for a reason or is it redundant?
Would the following code:
template <typename T>
void QVector<T>::append(const T &t)
{
// const T copy(t);
if (d->ref != 1 || d->size + 1 > d->alloc)
realloc(d->size, QVectorData::grow(sizeof(Data), d->size + 1, sizeof(T),
QTypeInfo<T>::isStatic));
if (QTypeInfo<T>::isComplex)
new (d->array + d->size) T(t);
else
d->array[d->size] = t;
++d->size;
}
template <typename T>
void QVector<T>::append(const T &t)
{
// const T copy(t);
if (d->ref != 1 || d->size + 1 > d->alloc)
realloc(d->size, QVectorData::grow(sizeof(Data), d->size + 1, sizeof(T),
QTypeInfo<T>::isStatic));
if (QTypeInfo<T>::isComplex)
new (d->array + d->size) T(t);
else
d->array[d->size] = t;
++d->size;
}
To copy to clipboard, switch view to plain text mode
do the same thing as the original code?
The same practice seems to be used in other functions of QVector as well like in QVector::fill():
template <typename T>
QVector<T> &QVector<T>::fill(const T &from, int asize)
{
const T copy(from); //is it really needed???
resize(asize < 0 ? d->size : asize);
if (d->size) {
T *i = d->array + d->size;
T *b = d->array;
while (i != b)
*--i = copy;
}
return *this;
}
template <typename T>
QVector<T> &QVector<T>::fill(const T &from, int asize)
{
const T copy(from); //is it really needed???
resize(asize < 0 ? d->size : asize);
if (d->size) {
T *i = d->array + d->size;
T *b = d->array;
while (i != b)
*--i = copy;
}
return *this;
}
To copy to clipboard, switch view to plain text mode
and probably in other classes too.
So, is this practice of creating a const copy (as an automatic variable) redundant or am I missing something???
Bookmarks