gpt4 book ai didi

C++:右值引用内存

转载 作者:可可西里 更新时间:2023-11-01 17:36:47 27 4
gpt4 key购买 nike

由于 c++ 提供对右值的引用,即主要用于执行移动语义和其他内存高效任务的右值引用。但是在下面的例子中,引用改变了文字的值,但是我们知道文字是只读的,所以引用怎么能改变一些只读变量的值呢。右值引用是分配它自己的内存还是它只是改变文字的值?

#include <iostream>
using namespace std;

int main()
{
int a = 5;
int&& b = 3;
int& c = a;
b++;
c++;
cout << " Value for b " << b << " Value for c " << c << endl;
}

其次,当为临时对象分配引用时,引用会处理该对象的数据。但是根据临时对象的定义,它们会在使用它们的表达式结束时被删除。如果临时对象内存不足,引用如何充当该临时对象的别名?

最佳答案

数字文字不能绑定(bind)到任何引用,无论是右值引用还是左值引用。从概念上讲,数字文字创建一个从文字值初始化的临时对象,这个临时对象可以绑定(bind)到右值引用或 const 左值引用 (int const& r = 17; ).似乎有关文字的相关引用是 5.1.1 [expr.prim.general] 第 1 段:

A literal is a primary expression. Its type depends on its form (2.14). A string literal is an lvalue; all other literals are prvalues.

将引用直接绑定(bind)到临时对象时,它的生命周期会延长,直到引用超出范围。生命周期问题的相关部分是 12.2 [class.temporary] 第 5 段:

The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:

  • A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.
  • A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.
  • The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.
  • A temporary bound to a reference in a new-initializer (5.3.4) persists until the completion of the full-expression containing the new-initializer.

关于C++:右值引用内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37518434/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com