什么是文字值的范围,以及编译器如何分配内存呢? [英] What is the scope of a literal value, and how does the compiler allocate memory to it?

查看:70
本文介绍了什么是文字值的范围,以及编译器如何分配内存呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  INT X = 12;

12 据说是整数文字,因此不能在左值使用。


  1. 编译器如何分配内存以一个文字?

  2. 什么是文字的范围有多大?

  3. 为什么我们不能得到它以&安培地址;?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.

  1. How does the compiler allocate memory to a literals?
  2. What is the scope of a literals?
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆