[英]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?当有两个原始数据类型的
std::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."我只发现“否则,*this 拥有的 memory 可能会在可能的情况下被重复使用。” (since C++11) on cppreference.com .
(C++11 起)在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?如果不能保证,这种情况可能是Copying std::vector: prefer assignment or std::copy?的答案。 , when
std::copy
would be preferred. ,当首选
std::copy
时。
Standard doesn't guarantee that there would be no allocations.标准不保证不会有分配。 According to the C++11 Standard the effect of
b = a;
根据C++11 标准
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())" .就好像
b.assign(a.begin(), a.end())
(b 的剩余元素被销毁,如果有的话)结果是“用 [a.begin(), a.结束())” 。 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" .与分配无关,但使用C++20 标准(可能更早)我们有一个附加声明: “使所有引用 b 的元素的引用、指针和迭代器无效” 。 Which means allocation is possible and the
capacity()
isn't mentioned anywhere in these guarantees to prevent it in your particular case.这意味着分配是可能的,并且在这些保证中的任何地方都没有提到
capacity()
以防止在您的特定情况下发生这种情况。
On the other hand, in practice, why would it reallocate the memory if there is enough already?另一方面,实际上,如果已经足够了,为什么还要重新分配 memory?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.