push_back 来自同一个向量的元素是否安全?

Is it safe to push_back an element from the same vector?(push_back 来自同一个向量的元素是否安全?)
本文介绍了push_back 来自同一个向量的元素是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..
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 来自同一个向量的元素是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

OpenGL transforming objects with multiple rotations of Different axis(OpenGL 变换不同轴多次旋转的对象)
GLFW first responder error(GLFW 第一响应者错误)
SOIL not linking correctly(SOIL 连接不正确)
Core profile vs version string? Only getting GLSL 1.3/OGL 3.0 in mesa 10.0.1(核心配置文件与版本字符串?在 mesa 10.0.1 中只获得 GLSL 1.3/OGL 3.0)
What is the range of OpenGL texture ID?(OpenGL 纹理 ID 的范围是多少?)
How taxing are OpenGL glDrawElements() calls compared to basic logic code?(与基本逻辑代码相比,OpenGL glDrawElements() 调用的繁重程度如何?)