为什么rvalue reference是lvalue

右值引用(rvalue reference) C++11 引入了右值引用(rvalue reference)的概念,这是为了支持移动语义(move semantics)和完美转发(perfect forwarding)而引入的新特性。右值引用允许我们高效地处理临时对象,避免不必要的拷贝,从而提高程序的性能。 阅读详情

gcc-4.9.2\libstdc++-v3\include\bits\stl_vector.h的代码:

      /**
       *  @brief  %Vector move constructor.
       *  @param  __x  A %vector of identical element and allocator types.
       *
       *  The newly-created %vector contains the exact contents of @a __x.
       *  The contents of @a __x are a valid, but unspecified %vector.
       */
      vector(vector&& __x) noexcept
      : _Base(std::move(__x)) { }

问题来了,x是个rvalue reference啊,为什么要std::move(x),_Base(x)不能直接调用_Base(&&)么?

这个很多文章,视频,书都会讲到的,x是个rvalue reference,但它是个lvalue,所以必须std::move(x)

听上去总是很蛋疼,还是没讲明白为什么啊。

讲明白的如下:

lvalue和rvalue在标准的[basic.lval]:

Expressions are categorized according to the taxonomy in Figure 1

然后Figure 1华丽丽的给出了expression的lvalue,rvalue,glvalue,xvalue,prvalue。。。但是很明确的一点是,这个分类是针对expression的一套分类系统,和类型没有关系。而lvalue reference,rvalue reference显然是两个reference类型,从属于类型系统。

回到上面的代码,__x的类型毫无疑问是rvalue reference,然后__x这个expression是显然归属于lvalue的,所以才有了std::move(__x)的使用。


C++11中的rvalue references(一):左值和右值(lvalue and rvalue) * “If you’re an experienced C++ programmer and are anything like me, you initially approached C++11 thinking, “Yes, yes, I get it. It’s C++, only more so.” But as you learned more, you were surpri 阅读详情

相关推荐

boost中cannot bind rvalue reference of type to lvalue of type问题

1.问题引出 最近在新的环境上编译以前使用过boost的c++程序,发现对boost的相关调用部分报错了,而且报错发生在boost的内部的hpp文件中 报错内容:cannot bind rvalue reference of type to lvalue of type 通过实际查看boost报错部分的代码,发现报错部分的代码类似于这样: main.cpp: #include <stdio.h> template<typename T> void f1(const T&

ciengwu的专栏 3608

《C++11标准库》3.1.5 Move语义和Rvalue Reference(右值引用)及Rvalue,Lvalue Reference(左值引用)的重载规则和返回Rvalue Reference

C++的一个最重要的特性之一就是支持 move semantic(搬迁语义/移动语义),这项语义更加贴合C++的主要设计目标:用以避免非必要拷贝(copy)和临时对象(temporary)。 首先,我们要知道为什么需要move语义,对于以下代码: 对于上述代码,我们将新对象插入集合中,后者提供一个成员函数可为传入的元素建立一份内部拷贝(internal copy) ,set.insert()简化模板可为: 这样的建立拷贝的方式是有用的,因为对于创建的对象x在被插入集合后,这个对象仍有可能被使用

weixin_60351940的博客 879

【Qt问题】error: cannot bind non-const lvalue reference of type ‘QFont&‘ to an rvalue of type ‘QFont‘

这个错误提示表明,在第 14 行的代码中,尝试将一个临时对象(rvalue)赋值给一个非常量左值引用(non-const lvalue reference)。对象的拷贝构造函数或者赋值运算符来创建一个非临时对象,然后将其传递给。函数中需要一个非临时对象作为参数。返回的对象是一个临时对象,而在。要解决这个问题,你可以考虑使用。

Fanjufei的博客 620

C++ 右值引用(Rvalue reference)

在调用移动构造函数和移动赋值运算符时,我们通过std::move()将std::string类型的参数转换为右值引用,并使用std::unique_ptr对其进行管理。这样可以有效减少内存分配和拷贝操作,提高代码的效率和可读性。消除不必要的内存分配和拷贝:右值引用可以将临时对象或返回值作为右值引用传递给函数,并在函数内部直接移动或转移其资源所有权,避免了不必要的内存分配和拷贝操作。实现移动语义:右值引用可以方便地实现移动构造函数和移动赋值运算符,从而提高移动语义的效率和可读性。

qq_41979948的博客 410

揭秘大型语言模型:从神经元到思维透明的奇妙旅程

这篇博客带你走进大型语言模型的内部世界,从神经元的小任务,到功能向量的团队合作,再到层间的协作和思维的透明化。掌握这些知识,能让你在开发中更高效地优化AI,在研究中更深入地探索模型的奥秘。建议多动手实践,把这些理论变成自己的能力!

数据与算法架构提升之路专栏 1527

Eureka自我保护机制

Eureka自我保护机制 默认情况下,当eureka server在一定时间内没有收到实例的心跳,便会把该实例从注册表中删除(默认是90秒),但是,如果短时间内丢失大量的实例心跳,便会触发eureka server的自我保护机制,比如在开发测试时,需要频繁地重启微服务实例,但是我们很少会把eureka server一起重启(因为在开发过程中不会修改eureka注册中心),当一分钟内收到的心跳数大量减少时,会触发该保护机制。可以在eureka管理界面看到Renews threshold和Renews(last

Soul_Ming的博客 548

c++11右值引用

1.  参考:c++11之左值、纯右值、将亡值   https://blog.csdn.net/StephenZou14/article/details/77817114     2.  std::forword()原型, 头文件&lt;utility&gt; lvalue (1) template &lt;class T&gt; T&amp;&amp; forw...

thinktalk的专栏 407

RK3568-Linux-麒麟系统---更新制作麒麟rootfs

RK3568 Linux系统 麒麟国产麒麟镜像

qiuzw2003的博客 5368

元编程: is_lvalue_reference<Tp>

判断是否为左值引用 #include <iostream> #include <type_traits> int main() { int a = 10; int& b = a; std::cout << "This Demo: is_lvalue_reference" << std::endl; if(std::is_lvalue_reference<int>::value) {

hit1524468的专栏 524

从Landsat 8到哨兵2号:手把手教你用ENVI处理不同卫星数据的NDVI(附常见错误排查)

本文详细解析了从Landsat 8到哨兵2号的多源遥感数据NDVI计算全流程,包括不同卫星的波段设置差异、ENVI处理步骤及常见错误排查。通过实战指南和代码示例,帮助用户高效处理NDVI数据,特别针对哨兵2号数据的特殊处理提供了专业建议,适用于植被监测和遥感分析。

weixin_27741699的博客 333

从入门到精通:HyperMesh实体选择全攻略(含2025新界面操作)

本文系统解析了HyperMesh从基础到高级的实体选择技巧,重点介绍了2025新界面的交互逻辑与效率提升。内容涵盖选择模式、框选方法、右键菜单高级选择、图形窗口选择器与命令面板的智能联动,以及利用浏览器和过滤器进行精准定位的实战指南,帮助用户显著提升前处理建模效率。

open4的博客 1097

lvalue / rvalue and lvalue reference / rvalue reference

表达式的类型 :type of an expression表达式的类别和表达式最终返回的对象、值、函数的类型相同。// 该表达式会在编译的时候确定 两个 int 相除,产生int类型的结果,因此 int 就是该表达式的类型。// 在c++中 auto 并不是一种动态类型,而是在编译时确定的,变量的类型在初始化时已经确定。// 算数运算符必须具有匹配类型的操作数 在计算 12.0 / 4;时,int 类型会被转换为 double 类型,然后进行除法运算。表达式的类型是在编译时确定的。

liu_12345_liu的博客 1113

Rust新手必看:如何用impl关键字实现面向对象三大特性(附完整代码示例)

本文面向Rust新手,详细解析如何利用impl关键字实现面向对象编程的封装、继承和多态三大特性。通过结构体封装、Trait定义共享行为以及Trait对象与泛型实现多态等完整代码示例,帮助开发者掌握Rust独特的面向对象设计模式,安全高效地构建应用程序。

weixin_29000991的博客 282

C++ lvalue,rvalue及rvalue reference

lvalue佔據了記憶體空間,壽命較長,可以將它想像為容器。 rvalue並未指向記憶體的任何地方,是暫時的,可以將它想像為容器裡的東西。

keineahnung2345的博客 760

Cibersort免疫浸润 --- 详细教程

免疫浸润是指免疫细胞如淋巴细胞、浆细胞、巨噬细胞等进入到组织或器官中,并在这些组织或器官中发挥免疫功能的过程。免疫细胞的浸润可以是炎症反应的一部分,也可以是针对感染、肿瘤或其他疾病的免疫应答的一部分。免疫浸润通过调节免疫反应和炎症反应的程度和类型,起到维护机体免疫平衡和清除异常细胞或病原体的作用。在某些情况下,免疫浸润可能导致炎症反应过度,引起组织损伤,例如自身免疫性疾病。因此,免疫浸润在许多疾病的诊断和治疗中都具有重要的意义。免疫浸润可以通过组织切片染色和免疫组织化学等方法观察和分析。

ZxVSaccount的博客 9119

simulink调用C代码函数-C Caller模块

simulink中如何调用写好的C代码函数?使用C Caller模块调用C代码。

weixin_40531919的博客 5684

lvalue & rvalue

看到人讨论隐式类型转换。大致摘一点,记录一下。#include #include class dummy{};class A{public: A(){} A(const dummy& d){} void foo(){std::cout  void foo() const {std::cout };void foo(A&){std::cout void foo(const A&){std::co

Mind Mining ™ 2039

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

C++基础-----rvalue与lvalue的区别

下面是我对这两个单词字面的意思的猜测: lvalue估计来源于left value。 在赋值语句中lvalue = rvalue;位置处于左边。就是可以修改的值。 rvalue估计来源于right value。处于赋值语句右边,是只读的不可修改的值。类似报 const结构 不能被 非const指针指向。 lvalue是可以赋值的,说明它是一...

weixin_39609623的博客 2057

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

C++标准模板(STL)- 类型支持 (类型特性,is_pointer,is_lvalue_reference,is_rvalue_reference)

检查 T 是否为指向对象指针或指向函数指针(但不是指向成员/成员函数指针)。若 T 是对象/函数指针类型,则提供等于 true 的成员常量 value 。否则, value 等于 false 。 检查 T 是否为左值引用类型。若 T 是左值引用类型,则提供等于 true 的成员常量 value ,否则, value 等于 false 。 检查 T 是否为右值引用类型。若 T 是右值引用类型,则提供等于 true 的成员常量 value ,否则, value 等于 false 。

qq_40788199的博客 1288

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

cannot bind non-const lvalue reference to an rvalue

C++编译报错:cannot bind non-const lvalue reference to an rvalue - 简书

z15f34的博客 188

C++11 auto、decltype、is_reference、is_rvalue_reference/is_lvalue_reference、typeid

【代码】C++11 auto、decltype、is_reference、is_rvalue_reference/is_lvalue_reference、typeid。

木牛的博客 116

lvalue 引用 && rvalue 引用

C++中的每个表达式要么是lvalue要么是rvalue。lvalue表示一个内存位置,而rvalue表示计算表达式的结果。 rvalue引用是对有名称变量的引用,并允许变量表示的内存通过lvalue引用来访问。 rvalue引用是对包含表达式结果的内存位置的引用。 总之,表达式的结果和函数内定义的变量都属于临时变量,即rvalue。   int && num {2*x+3...

weixin_33860528的博客 343

left value. right value. reference. const reference

// 以下是我个人的理解,如有错误请告知,非常感谢你。 #include #include using namespace std; string one("cute"); // non-const lvalue const string two("fluffy"); // const lvalue string three() // non-cons

I will work my left life for my family 3533

cannot bind non-const lvalue reference of type ‘xxx&‘ to an rvalue of type ‘xxx‘

文章目录报错代码报错原因解决方案 报错代码 #include<iostream> using namespace std; class Complex{ private: double r,i; public: Complex(double _r,double _i=0):r(_r),i(_i){} double re() {return r;} double im() {return i;} void print(){ cout <

weixin_53366150的博客 3731

Lvalue, Rvalue, Xvalue, Prvalue, Glvalue

Lvalue, Rvalue, Xvalue, Prvalue, Glvalue c++11中关于什么是lvalue, 什么是rvalue, 什么是xvalue, 什么是prvalue, 什么是… 一直搞得我晕头转向的, 今天下定决心一定要把它搞定, 写了一个程序来判断lvalue, rvalue, prvalue等 1 namesp...

weixin_34168880的博客 128

c++11,rvalue reference

http://blogs.msdn.com/b/vcblog/archive/2009/02/03/rvalue-references-c-0x-features-in-vc10-part-2.aspx Part 1of this series coveredlambdas,auto, andstatic_assert. Today, I'm going to talk...

weixin_30411997的博客 428
上一篇: Effective Modern C++ 笔记 第七章 The Concurrency API
下一篇: 欢迎使用CSDN-markdown编辑器
rreference
博客等级 码龄12年 0粉丝 26原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值