foriequals0
foriequals0

Reputation: 181

Understanding QVector append() - Why does it copy conditionally?

Here is the implementation of QVector's append() from github:

template <typename T>
void QVector<T>::append(const T &t)
{
    if (d->ref != 1 || d->size + 1 > d->alloc) {
        const T copy(t);
        realloc(d->size, QVectorData::grow(sizeOfTypedData(), d->size + 1, sizeof(T),
                                           QTypeInfo<T>::isStatic));
        if (QTypeInfo<T>::isComplex)
            new (p->array + d->size) T(copy);
        else
            p->array[d->size] = copy;
    } else {
        if (QTypeInfo<T>::isComplex)
            new (p->array + d->size) T(t);
        else
            p->array[d->size] = t;
    }
    ++d->size;
}

Why does it need to make a copy of t if the number of references to the vector != 1 or it needs to resize and why does it make a copy only for these conditions?

A related question has been asked here, but in the code there a copy of t is always made before appending to the underlying array.

Upvotes: 1

Views: 2684

Answers (1)

nwp
nwp

Reputation: 9991

At a quick glance it is probably because the if part is for when the vector reallocates whereas the else part is for when it doesn't. When it does reallocate the user could have done vector.append(vector[index]) in which case t would become invalid after the reallocation, therefore a copy must be made before reallocating. In the else part without a reallocation t will stay valid and no copy is necessary.

Upvotes: 4

Related Questions