通过引用返回已销毁的局部变量的成员
Returning by reference a member of a destroyed local variable
有人可以解释一下这是否可以吗?
#include <iostream>
#include <vector>
struct A {
std::vector<int> numbers;
~A() {std::cout << "A destroyed.n";}
const std::vector<int>& getNumbers() const {return numbers;}
std::vector<int> getNumbersByValue() const {return numbers;}
};
std::vector<int> foo() {
A a;
a.numbers = {1,2,3,4,5};
// return a.getNumbersByValue(); // This works of course.
return a.getNumbers(); // Is this line wrong?
}
void useVector(std::vector<int>& v) {
for (int i = 6; i <=10; i++)
v.push_back(i);
}
int main() {
auto v = foo(); // A destroyed.
for (int x : v) std::cout << x << ' '; // 1 2 3 4 5
std::cout << 'n';
useVector(v);
for (int x : v) std::cout << x << ' '; // 1 2 3 4 5 6 7 8 9 10
}
既然a
在 foo() 中被销毁了,那么 a.numbers 也被销毁了,对吧? 如果 foo() 使用 A::getNumbersByValue()
返回 a.numbers 的副本,那么一切都很好。 但是上面我使用的是getNumbers()
,它通过引用返回它。 向量在 foo() 结束后仍然存在。 所以我将向量传递到函数useVector
,看看它是否仍然存在,它确实存在。 那么这里一切都好吗?
由于foo
按值(而不是按引用)返回其返回值,因此foo
创建要返回的向量的副本。 它从它从getNumbers
返回的引用复制,作为它销毁局部变量a
的一部分,所以在它进行复制时,引用仍然有效。
所以这段代码很好。
相关文章:
- 使用的未初始化局部变量'Quick'
- 修复未初始化的局部变量错误
- 局部变量保留函数中的值
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 将引用分配给局部变量,如果局部变量超出范围,它会超出范围吗?
- Gnuplot_i.hpp C++接口绘制局部变量而不是文件
- 如何在函数外部访问函数中局部变量的值?
- 局部堆栈变量成员的返回值优化
- 如果对象是通过 new 创建的,则成员函数的局部变量在哪里创建?
- 为什么C++编译器不优化对结构数据成员的读取和写入,而不是不同的局部变量?
- 使用局部变量中的类成员类型
- 初始化列表,局部变量与数据成员
- 微优化:使用局部变量与.class成员进行迭代
- C++类设计:成员和局部变量
- 通过引用返回已销毁的局部变量的成员
- 将局部变量作为向量的成员传递给被调用者
- c++局部与成员变量性能
- 临时缓冲区:局部或成员变量
- 访问与局部变量(或参数)同名的成员字段
- c++性能:局部变量vs数据成员