T
Tom
I come from C but don't really understand why in C++ you can return a temporary object
from a function.
For example:
class Test {
public:
Test() { cout << "Address of object: " <<this <<endl; }
~Test() { }
};
Test func() {
Test tmp;
cout << "func(): Address of tmp: " << &tmp <<endl;
return tmp;
}
int main() {
Test a = func();
cout <<"main(): Address of a: " <<&a <<endl;
}
Output:
func(): Address of tmp: 0x22ff30
main(): Address of a: 0x22ff30
The output shows the same address on the stack for the two objects, but the same code in C
using structures instead of classes shows a different address ("tmp" local to the func stack
and "a" local to main).
So I have some questions:
Aren't local variables (and objects) created in the stack?
If so, why the local object is not destroyed after the function call?
Shouldn't they point to different addresses, with a local copy for each one?
Thanks for any clearing of confusion you can contribute...
from a function.
For example:
class Test {
public:
Test() { cout << "Address of object: " <<this <<endl; }
~Test() { }
};
Test func() {
Test tmp;
cout << "func(): Address of tmp: " << &tmp <<endl;
return tmp;
}
int main() {
Test a = func();
cout <<"main(): Address of a: " <<&a <<endl;
}
Output:
func(): Address of tmp: 0x22ff30
main(): Address of a: 0x22ff30
The output shows the same address on the stack for the two objects, but the same code in C
using structures instead of classes shows a different address ("tmp" local to the func stack
and "a" local to main).
So I have some questions:
Aren't local variables (and objects) created in the stack?
If so, why the local object is not destroyed after the function call?
Shouldn't they point to different addresses, with a local copy for each one?
Thanks for any clearing of confusion you can contribute...