加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 文字值的范围是什么,编译器如何为其分配内存?

发布时间:2020-12-16 10:20:53 所属栏目:百科 来源:网络整理
导读:int x = 12; 12表示是整数字面值,因此不能用于LValue. 编译器如何为文字分配内存? 文字的范围是什么? 为什么我们不能在其范围内使用 12获得其地址? 解决方法 好问题中的错误示例. 但问题仍然有效: 我们试试吧: Foo getFoo() {return Foo();}int func(){
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.

How does the compiler allocate memory to a temporary object?

未定义到编译器.
但是在堆栈帧上分配更多的内存并将其保存在那里真的很容易.然后销毁它并减小堆栈帧的大小(尽管这个答案对你不应该做的底层硬件做了很多假设(最好只把它想象为编译器做魔术)).

What is the scope of a temporary object?

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

Why can’t we get its address with an &12 in its scope?

在问题12中不是临时对象.它是一个整数字面值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读