我有以下代码.
#include <iostream>
int * foo()
{
int a = 5;
return &a;
}
int main()
{
int* p = foo();
std::cout << *p;
*p = 8;
std::cout << *p;
}
Run Code Online (Sandbox Code Playgroud)
而代码只是运行而没有运行时异常!
输出是 58
怎么会这样?本地变量的内存不能在其功能之外无法访问吗?
我有一些关于从函数返回对局部变量的引用的问题:
class A {
public:
A(int xx)
: x(xx)
{
printf("A::A()\n");
}
};
const A& getA1()
{
A a(5);
return a;
}
A& getA2()
{
A a(5);
return a;
}
A getA3()
{
A a(5);
return a;
}
int main()
{
const A& newA1 = getA1(); //1
A& newA2 = getA2(); //2
A& newA3 = getA3(); //3
}
Run Code Online (Sandbox Code Playgroud)
我的问题是=>
执行getA1()是否正确?我觉得它是错误的,因为它返回局部变量的地址或临时变量.
main(1,2,3)中的哪些陈述会导致未定义的行为?
在const A& newA1 = getA1();做标准的保证,暂时由const引用约束不会被破坏,直到引用超出范围是什么?
一个基本问题,我不确定答案.以下功能是否有效?
std::vector<int> & test_function() {
std::vector<int> x;
// do whatever
return x;
}
Run Code Online (Sandbox Code Playgroud)
如果是这样,为什么?函数返回后,程序不应该从堆栈中删除x吗?谢谢.