[英]C++ function returns a valid 'by reference' object after destroy
I'm using visual studio 2010 compiler and I'm trying to understand the output of this program. 我正在使用Visual Studio 2010编译器,并且试图了解该程序的输出。
Code: 码:
#include <iostream>
using namespace std;
class A
{
public:
int i;
A()
{
i=0; cout<<"constructing A..\n";
}
A(int a): i(a)
{
cout<<"constructing A with argument\n";
}
A(A& a)
{
i=a.i;
cout<<"copy constructor\n";
}
~A()
{
cout<<"destructing a: " << i << endl;
}
};
A& f(A b)
{
return A(25);
}
void main()
{
A m;
cout << "i = " << f(m).i << endl;
}
Output: 输出:
constructing A.. 建造A ..
copy constructor 复制构造函数
constructing A with argument 用参数构造A
destructing a: 25 破坏:25
destructing a: 0 破坏:0
i = 25 我= 25
destructing a: 0 破坏:0
From my understanding, A(25) returned by reference and then destroyed, so why does it print the value of i: 'i = 25'? 根据我的理解,A(25)通过引用返回然后销毁,那么为什么要打印i的值:“ i = 25”?
The program has undefined behavior. 该程序具有未定义的行为。 Nevertheless the output can be as you expected because the memory occupied by the non alive object can be not overwritten yet.
但是,由于未活动对象占用的内存尚未被覆盖,因此输出可以达到您的预期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.