c++ 返回引用/堆栈内存堆栈、内存

2023-09-07 03:07:18 作者:,伱別想別念別碰

一个我不确定答案的基本问题.跟随功能有效吗?

A basic question that I'm not sure of the answer. Is the follow function valid?

std::vector<int> & test_function() {
   std::vector<int> x;

   // do whatever

   return x;
}

如果是这样,为什么?函数返回后程序不应该从堆栈中删除 x 吗?谢谢.

If so, why? Shouldn't the program delete x from the stack after the function returns? Thanks.

推荐答案

行为未定义.您不应该返回对局部变量的引用.

The behavior is undefined. You shouldn't return references to local variables.