我发现了奇怪的行为,并希望了解它的工作方式和原因(在msvc 14.0,Visual Studio 2015上测试)。
让我们假设我们有结构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; }
};
我们有以下代码:
{
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
问题是:
看起来有时引用可以处理对象,有时候不会。是否有任何澄清?