有人可以解释一下这是否可以吗?
#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()
,它通过引用返回它。该 vector 在 foo() 结束后仍然存在。因此,我将 vector 传递给函数 useVector
以查看它是否仍然存在,它确实存在。那么这里一切都好吗?
最佳答案
由于 foo
按值(而不是按引用)返回其返回值,因此 foo
制作要返回的 vector 的拷贝。它从 getNumbers
返回的引用中复制作为返回的一部分 before 它破坏局部变量 a
,所以在它使拷贝,引用仍然有效。
所以这段代码没问题。
关于c++ - 通过引用返回已销毁的局部变量的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27712458/