让我们从C中的示例代码开始:
#include <vector> #include <iostream> int main() { std::vector<int> vec; vec.push_back(0); for (int i = 1; i < 5; i++) { const auto &x = vec.back(); std::cout << "Before: " << x << ","; vec.push_back(i); std::cout << "After: " << x << std::endl; } return 0; }
代码用g test.cc -std = c 11 -O0编译,结果如下:
Before: 0,After: 0 Before: 1,After: 0 Before: 2,After: 2 Before: 3,After: 3
我期待第二行输出
Before: 1,After: 1
因为x是对向量中的项的引用,不应通过将项附加到向量来修改该项.
但是我现在还没有阅读反汇编代码或进行任何其他调查.此外,我不知道这是否是语言标准中的未定义行为.
我想要解释一下.谢谢.
解决方法
push_back可以导致重新分配,如果我们查看
draft C++ standard部分23.3.6.5向量修饰符说:
void push_back(const T& x);
void push_back(T&& x);
Remarks: Causes reallocation if the new size is greater than the old capacity. If no reallocation happens,all the iterators and references before the insertion point remain valid.
我们可以看到back给了我们一个参考,所以如果有重新分配它将不再有效.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。