【发布时间】:2020-05-10 17:37:59
【问题描述】:
我发现了 std::reference_wrapper 提供的好工具,但这种行为对我来说听起来很奇怪。
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <numeric>
int main()
{
std::vector<int> vectorA(10);
std::vector<std::reference_wrapper<int>> vec;
std::iota(vectorA.begin(),vectorA.end(),0);
for(auto i: vectorA){
std::cout << "In vectorA: "<< i << " ";
}
std::cout << "\n";
for(unsigned i=0; i< vectorA.size(); i++){
vec.push_back(std::ref(vectorA[i]));
}
for(auto i: vec){
std::cout << "In vec: "<< i << " ";
}
std::cout << "\n";
vectorA.erase(vectorA.begin()+9);
for(auto i: vectorA){
std::cout << "In vectorA: "<< i << " ";
}
std::cout << "\n";
for(auto i: vec){
std::cout << "In vec: "<< i << " ";
}
std::cout << "\n";
}
为什么擦除 vec (vectorA[9]) 中引用的元素不会影响矢量 vec 的大小?此外,为什么 vec[9] 仍然可以访问?
【问题讨论】:
-
this behaviour sounds weird to me此行为未定义。 :) C++ 不能防止愚蠢的事情发生。 -
因为您有责任确保被引用的对象比引用更有效。你会得到与指针或普通引用相同的行为。这就是
c++的工作方式。没有你的要求,它不会为你神奇地做事。
标签: c++ reference std reference-wrapper