返回如下所示的引用包装器是否危险?
std::vector<std::reference_wrapper<int>> foo() {
int x = 10;
std::vector<std::reference_wrapper<int>> vec;
vec.push_back(x);
return vec;
}
foo2() {
std::cout << foo()[0] << std::endl;
}
我假设局部/堆栈变量x可能在foo2()
中丢失。
函数std::vector<std::reference_wrapper<int>> foo();
实际上返回一个指向位于函数堆栈中的局部变量的引用的向量,该堆栈已被销毁。悬空引用的向量。