#include <iostream>
using namespace std;
class A
{
public :
A()
{
cout<<"constructor is called"<<endl;
}
~A()
{
cout<<"destructor is called"<<endl;
}
A(const A &s)
{
cout<<"copy constructor is called"<<endl;
}
};
A beta()
{
A a;
cout<<"mem location a : "<<&a<<endl;
return a;
}
int main(int argc, char** argv) {
A b = beta();
cout<<"mem location b : "<<&b<<endl;
return 0;
}
The above program generates the following output :
constructor is called
mem location a : 0x7ffc12bdaf77
mem location b : 0x7ffc12bdaf77
destructor is called
As far as I understand just a single instance of A was created rather than 2 instances for A a and A b, because of copy elision or return value optimisation. But looking at above program from a memory perspective, object a is inside the stack activation record or stack space of function beta and has a memory location 0x7ffc12bdaf77 . When it returns from beta, copy elision makes object b just same as object a rather than copying it. So, now b also has the address 0x7ffc12bdaf77 . I am unable to understand if b is still a local of the function main and present inside its stack space, how can it occupy a memory outside main's stack space ?
Aucun commentaire:
Enregistrer un commentaire