从同一个向量push_back一个元素是安全的吗? [英] Is it safe to push_back an element from the same vector?
问题描述
vector<int> v;
v.push_back(1);
v.push_back(v[0]);
如果第二个push_back导致重新分配,向量中第一个整数的引用将不再有效。这是不安全的吗?
If the second push_back causes a reallocation, the reference to the first integer in the vector will no longer be valid. So this isn't safe?
vector<int> v;
v.push_back(1);
v.reserve(v.size() + 1);
v.push_back(v[0]);
这样安全吗?
推荐答案
它看起来像是 http:// www.open-std.org/jtc1/sc22/wg21/docs/lwg-closed.html#526 将此问题(或与其非常相似的内容)视为标准中的潜在缺陷:
It looks like http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-closed.html#526 addressed this problem (or something very similar to it) as a potential defect in the standard:
1)可以在执行期间更改const引用所执行的参数
函数
1) Parameters taken by const reference can be changed during execution of the function
例如:
给定std :: vector v:
Given std::vector v:
v.begin ,v [2]);
v.insert(v.begin(), v[2]);
可以更改
建议的解决方案是这不是缺陷:
The proposed resolution was that this was not a defect:
vector :: insert(iter,value)因为标准
不允许它不工作。
vector::insert(iter, value) is required to work because the standard doesn't give permission for it not to work.
这篇关于从同一个向量push_back一个元素是安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!