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

标签 c++ function reference

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

#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/

相关文章:

c++ - 返回对临时的引用

c++ - 如何在 C++ 中创建一个运行时间计数器并允许用户同时输入的循环(非阻塞用户输入)

c++ - 使用指针初始化结构数组 - C++ ...?

c++ - 类中的静态成员是如何分配的?

C++ 未知类型名称 'string'

php - 尝试使用 jquery .load 根据表单中的特定输入将 PHP mysql 行打印到 div 中

javascript - 有人可以解释一下参数如何传递该值吗?

javascript - 如何暂停并调用嵌套 for 循环内的函数?

javascript - 如何确定列表中的位置以插入 div

c++ - 如何在 C++ 中返回引用