int x = 12;
12
被认为是整数文字,因此不能在 LValue 中使用。
- 编译器如何为文字分配内存?
- 文字的范围是什么?
- 为什么我们无法获取其范围内包含 &12 的地址?
好的,问题中的例子不好。
但问题仍然有效:
咱们试试吧:
Foo getFoo() {return Foo();}
int func()
{
getFoo().bar(); // Creates temporary.
// before this comment it is also destroyed.
// But it lives for the whole expression above
// So you can call bar() on it.
}
int func2()
{
Foo const& tmp = getFoo(); // Creates temporary.
// Does not die here as it is bound to a const reference.
DO STUFF
} // tmp goes out of scope and temporary object destroyed.
// It lives to here because it is bound to a const reference.
编译器如何为临时对象分配内存?
Undefined up-to the compiler.
But it would be real easy to allocate a tiny bit more memory onto the stack frame and hold it there. Then destroy it and reduce the size of the stack frame (though this answer makes a whole lot of assumptions about the underlying hardware that you should never do (best just to think of it as the compiler doing magic)).
临时对象的范围是什么?
临时对象一直存在到表达式结束(通常是;
) 除非它绑定到 const 引用。如果它绑定到 const 引用,那么它也存在于该引用所属范围的末尾(有一些例外(如构造函数))。
为什么我们无法获取其范围内包含 &12 的地址?
问题12中不是临时对象。
它是一个整数文字。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)