C:右值参考存储器

前端之家收集整理的这篇文章主要介绍了C:右值参考存储器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
由于c提供对​​rvalues的引用,即rvalue引用,其主要用于执行移动语义和其他存储器有效任务.但是在下面的例子中,引用是改变文字的值,但是我们知道文字是只读的,所以引用如何改变某些只读变量的值.右值引用是否分配了它自己的内存,或者它只是更改了文字的值?
#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;
}

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

解决方法

数字文字不能绑定到任何引用,既不是右值引用也不是左值引用.从概念上讲,数字文字创建一个从文字值初始化的临时对象,这个临时对象可以绑定到右值引用或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.

将引用直接绑定到临时引用时,它的生命周期会延长,直到引用超出范围.终身问题的相关部分是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&C++相关文章