简体   繁体   中英

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.

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..
copy constructor
constructing A with argument
destructing a: 25
destructing a: 0
i = 25
destructing a: 0

From my understanding, A(25) returned by reference and then destroyed, so why does it print the value of 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM