Pushing vector member into vector during expand: vector.push_back(vector[0])

I'm doing custom vector class in C++. I have a question about such code:

    vector<T> vec;
    vec.push_back(one);
    vec.push_back(two);
    vec.push_back(vec[0]);

Definition of push_back is as follows:

    void push_back(const T & v)

to avoid unnecessary copying. It's implementation looks like

    if (size == capacity)
    {
        allocate new storage
        copy old values into new storage
        // 2
        delete old storage
        fix pointers and counters
    }
    // 1
    copy v at the end of storage

The problem arises if we want to push element that is already in vector AND vector needs to expand (size is equal to its capacity). If we do it (vec.push_back(vec[0])) then at // 1, it is already deallocated. So we need to have a copy of it. Another alternative is adding it during expansion, somewhere at // 2 but this doesn't seem pretty.

How would you resolve this?

7
задан John 7 May 2011 в 10:24
поделиться