什么是字面值的范围,以及编译器如何为其分配内存?(What is the scope of a literal value, and how does the compiler allocate me

编程入门 行业动态 更新时间:2024-10-27 00:35:07
什么是字面值的范围,以及编译器如何为其分配内存?(What is the scope of a literal value, and how does the compiler allocate memory to it?) int x = 12;

12被认为是整数字面量,因此不能在LValue中使用。

编译器如何为文本分配内存? 文字的范围是什么? 为什么我们不能在它的范围内得到一个&12的地址? 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?

最满意答案

好的问题中的坏榜样。 但问题仍然有效: 咱们试试吧:

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.

编译器如何将内存分配给临时对象?

未定义的编译器。 但是,将更多的内存分配到堆栈帧并将其保留在那里真的很容易。 然后摧毁它并减小堆栈框架的大小(尽管这个答案对底层硬件做了大量的你永远不应该做的假设(最好只是把它看作是编译器在做魔术))。

什么是临时对象的范围?

临时对象一直存在到表达式的末尾(通常是; ),除非它被绑定到一个const引用。 如果它绑定到一个常量引用,那么它就存在于引用所属范围的末尾(有一些例外(如构造函数))。

为什么我们不能在它的范围内得到一个&12的地址?

在问题12中不是一个临时对象。 它是一个整数文字。

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.

更多推荐

本文发布于:2023-07-26 02:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1269615.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:编译器   字面   为其   分配   内存

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!