什么是文字值的范围,以及编译器如何分配内存呢? [英] What is the scope of a literal value, and how does the compiler allocate memory to it?
问题描述
INT X = 12;
12
据说是整数文字,因此不能在左值使用。
- 编译器如何分配内存以一个文字?
- 什么是文字的范围有多大?
- 为什么我们不能得到它以&安培地址;?12在其范围内
OK坏的问题的例子。结果
但问题是仍然有效:结果
让我们试试:
美孚的getFoo(){返回美孚();}INT FUNC()
{
的getFoo()条()。 //创建临时的。
//之前对此有何评论它也被破坏。
//但它生活在整个前$ P $以上pssion
//所以,你可以调用吧()就可以了。
}INT FUNC2()
{
富常量和放大器; TMP =的getFoo(); //创建临时的。
//因为它绑定到const引用不死在这里。 做东西
} // TMP超出范围并销毁临时对象。
//它生活于这里,因为它绑定到const引用。
编译器如何分配内存来临时对象?
块引用>未定义先进的编译器。结果
<子>不过,这将是真正的轻松分配更多的一点点记忆到堆栈帧并保持在那里。然后摧毁它,并减少堆栈帧的大小(虽然这个答案让一大堆关于底层的硬件,你不应该做的假设(充其量只是把它作为编译器做魔术))。
什么是临时对象的范围有多大?
块引用>的临时对象的生活,直到前pression的结束(通常是
;
),除非它被绑定到一个const引用。如果它被绑定到一个const引用则活到那么结束的范围,参考所属的太(除少数例外(如构造函数))。
为什么我们不能得到与地址的&功放;在其范围内12
块引用>在第12题是不是temporay对象。结果
它是一个整数文字。int x = 12;
12
is said to be integer literal, and therefore can't be used in the LValue.
- How does the compiler allocate memory to a literals?
- What is the scope of a literals?
- Why can't we get its address with an &12 in its scope?
解决方案OK Bad example in the question.
But the question is still valid:
Lets try: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.
How does the compiler allocate memory to a temporary object?
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)).What is the scope of a temporary object?
The temporary object lives until the end of the expression (usually the
;
) unless it is bound to a const reference. If it is bound to a const reference then it lives to then end of the scope that the reference belongs too (with a few exceptions (like constructors)).Why can't we get its address with an &12 in its scope?
In the question 12 is not a temporay object.
It is an integer literal.这篇关于什么是文字值的范围,以及编译器如何分配内存呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!