简体   繁体   中英

Allocation free std::vector copy when using assignment operator

When having two instances of std::vector with a primitive data type, having same size and capacity, is there a guarantee that copying via the copy assignment operator will not re-allocate the target vector?

Example:

const int n = 3;

std::vector<int> a, b;

// ensure defined capacity
a.reserve(n);
b.reserve(n);

// make same size
a.resize(n);
b.resize(n);

// set some values for a
for (int i = 0; i < n; i++)
{
    a[i] = i;
}

// copy a to b: allocation free?
b = a;

I've only found "Otherwise, the memory owned by *this may be reused when possible." (since C++11) on cppreference.com . I was hoping for a "must" instead of "may".

If there should be a positive answer for a more general case such as "same size is enough", even better.

If there should be no guarantee, this case could be an answer to Copying std::vector: prefer assignment or std::copy? , when std::copy would be preferred.

Standard doesn't guarantee that there would be no allocations. According to the C++11 Standard the effect of b = a; is as if b.assign(a.begin(), a.end()) (with surplus b's elements destroyed, if any) which result is "Replaces elements in b with a copy of [a.begin(), a.end())" . Nothing about allocations but with the C++20 Standard (maybe earlier) we have an additional statement: "Invalidates all references, pointers and iterators referring to the elements of b" . Which means allocation is possible and the capacity() isn't mentioned anywhere in these guarantees to prevent it in your particular case.

On the other hand, in practice, why would it reallocate the memory if there is enough already?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM