Is it safe to push_back an element from the same vector?(push_back 来自同一个向量的元素是否安全?)
问题描述
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.insert(v.begin(), v[2]);
v.insert(v.begin(), v[2]);
v[2] 可以通过移动向量的元素来改变
v[2] can be changed by moving elements of vector
提议的解决方案是这不是缺陷:
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 来自同一个向量的元素是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:push_back 来自同一个向量的元素是否安全?
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
