I have been learning C++ and programmed this out of curiosity:
#include <iostream>
class A {};
class B {
public:
~B() {}
};
A get_a() {
A a;
std::cout << &a << '\n';
return a;
}
B get_b() {
B b;
std::cout << &b << '\n';
return b;
}
int main() {
A a = get_a();
std::cout << &a << '\n';
B b = get_b();
std::cout << &b << '\n';
return 0;
}
I got this as the ouput:
0x61fedf
0x61ff0f
0x61ff0e
0x61ff0e
This implies that a new object is constructed in the case of A, but the lifetime of B is simply extended.
Can anyone explain this to me? I am currently writing a library and don't want to have any incorrect preconceptions.