I found strange behavior and would like to understand how and why it works the way it does (tested on msvc 14.0, Visual Studio 2015).
Lets assume we have structure test_struct
struct test_struct
{
test_struct() : _number(5) {}
int _number;
~test_struct()
{
static int i = 0;
std::cout << i++ << std::endl;
}
test_struct& get_me() { test_struct a; return a; }
};
And we have following code:
{
test_struct(); //(0) will be written 0, because object was created and died just at same moment, because it's scope is a point of it's creation.
test_struct struct2; //(1) nothing will be written, because object is still in scope
test_struct& ref1 = struct2.get_me(); //(2) trying to get reference to object that is out of scope, keeping reference to object do not save it. Will be written 1.
test_struct& ref2 = test_struct(); //(3) Nothing will be written !!?? Despite fact, that object was created similar as at (0), so had to die immediately, and despite fact, that keeping reference to such object do not save it, as we learned from (2)
{
test_struct& ref3 = struct2; //nothing will be written, because moving out of reference scope do not destruct object
}
} //will be written 2 and 3, because now moving out of reference scope destructs object
Questions are:
- If existing reference can handle object existing, why line (2) leads to undefined behavior and losing object?
- If existing reference can't handle object, why there is no destruction at line (3), and it happens at moment when reference leaving scope?
- If object without name constructed inside any scope live until exit from scope, why at line (0) there were destruction of such object?
- If object without name constructed inside any scope DON'T live until exit from scope, and reference do not handle objects, why object constructed without name at line (3) was not destructed after created?
It looks like sometimes reference can handle object, sometimes not. Does there exists any clarification on that?