考虑我们有一个按值返回的函数:
int func() {
int x = 10; // create local variable x with value of 5
return x; // create temporary copy of x which is returned, local variable x is destroyed
}
int main()
{
int y = func(); // temporary copy of x is copied to y, when it hits`;` the temporary object is destroyed
return 0;
}
如果我在上面的评论中所说的内容有误,请纠正我。
现在我们可以通过对它进行常量引用来延长临时对象的生命周期。
int main()
{
const int & y = func(); // now the temporary object (R-value) is not destroyed when it hits `;` thus the life time is lenghtened.
return 0;
}
问题是:由于我创建了一个对应该被销毁的临时对象的常量引用,这是否意味着cout << &y << endl
将打印该临时对象的地址,因为引用只是“别名”?那些临时对象(R值)存储在内存中的哪里(我使用原始类型 int 但它可能是类)?