通过引用返回已销毁的局部变量的成员

Returning by reference a member of a destroyed local variable

本文关键字:局部变量 成员 引用 返回      更新时间:2023-10-16

有人可以解释一下这是否可以吗?

#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的一部分,所以在它进行复制时,引用仍然有效。

所以这段代码很好。