C++非常量左值引用只能接受左值

  想了解右值引用和移动构造函数的请看这篇文章,强烈推荐:架构师大神带你读懂C++ - 微策略中国的文章 - 知乎
https://zhuanlan.zhihu.com/p/93155995
1.非常量引用接受右值的错误例子
  首先介绍一下左值(lvalue)和右值(rvalue),C++所有的值必属于左值或者右值,区分左右值有一个简单的方法:若可用"&"符号对表达式取地址,那么为左值,不能为右值。一般来说,临时变量,lambda表达式和字面量都属于右值。如:int i=0; i就是左值,0就是右值。
  看如下代码:

#include <iostream>
using namespace std;
int g_constructNum = 0;
int g_copyConstructNum = 0;
int g_deleteNum = 0;
class A {
private:
    int m_value;
public:
    A(int value) :m_value(value) 
    {
        std::cout << "construct: " << ++g_constructNum << std::endl;
    }
    A(const A& a)
    {
        std::cout << "copy construct: " << ++g_copyConstructNum << std::endl;
    }
    int getValue()
    {
        return m_value;
    }
    ~A()
    {
        std::cout << "destruct: " << ++g_deleteNum << std::endl;
    }
};
A getA(int value)
{
    return A(value);
}
int main()
{
    A &a=getA(1);
    int testValue = a.getValue();
    std::cout << "testValue: " << testValue << std::endl;
    return 0;
}

  这段代码我在VS2017编译器试了下,没报错,大概是因为VS编译器的优化,让getA(1)返回的对象存续到了函数结束,我在如下2个网上编译器试验都是报错的:
http://ideone.com/
http://coliru.stacked-crooked.com/
  报错的结果为:
图片说明
  大意就是非常量左值引用不能绑定右值,因为return A(value);只能产生一个临时的对象,而A &a=getA(1),引用绑定了一个临时对象,在没有优化的编译器,临时对象在A &a=getA(1)这行代码结束后就会销毁,这里就会导致报错。那要怎么解决呢?
2.解决方案
2.1 改为常量引用接受右值
  如下代码:

#include <iostream>
using namespace std;
int g_constructNum = 0;
int g_copyConstructNum = 0;
int g_deleteNum = 0;
class A {
private:
    int m_value;
public:
    A(int value) :m_value(value) 
    {
        std::cout << "construct: " << ++g_constructNum << std::endl;
    }
    A(const A& a)
    {
        std::cout << "copy construct: " << ++g_copyConstructNum << std::endl;
    }
    int getValue() const
    {
        return m_value;
    }
    ~A()
    {
        std::cout << "destruct: " << ++g_deleteNum << std::endl;
    }
};
A getA(int value)
{
    return A(value);
}
int main()
{
    const A &a = getA(1);
    int testValue = a.getValue();
    std::cout << "testValue: " << testValue << std::endl;
    return 0;
}

  改为常量左值引用,常量左值引用在c98中被称为"万能“引用类型,右值的生命周期和就会和引用相同,输出也会是:
  construct: 1
  testValue: 1
  destruct: 1
  所以,不要用非常量左值引用绑定右值

所以一般我们也会用const A&作为函数参数,既能接受左值,也能接受右值,某些情况下你只用引用的话可能传进来的是临时变量就报错了,同时使用const A&传入不会产生拷贝也不会改变传入的变量,非常好以及方便,图片来自:架构师大神带你读懂C++ - 微策略中国的文章 - 知乎
https://zhuanlan.zhihu.com/p/93155995
图片说明
图片说明

图片说明

2.2使用右值引用绑定右值
  有的人可能想,我的int getValue()函数不想改为const,又想让程序正常运行,怎么办呢,右值引用就出现了,我们可以通过右值引用来延长临时右值的生命周期,代码如下:

#include <iostream>
using namespace std;
int g_constructNum = 0;
int g_copyConstructNum = 0;
int g_deleteNum = 0;
class A {
private:
    int m_value;
public:
    A(int value) :m_value(value) 
    {
        std::cout << "construct: " << ++g_constructNum << std::endl;
    }
    A(const A& a)
    {
        std::cout << "copy construct: " << ++g_copyConstructNum << std::endl;
    }
    int getValue()
    {
        return m_value;
    }
    ~A()
    {
        std::cout << "destruct: " << ++g_deleteNum << std::endl;
    }
};
A getA(int value)
{
    return A(value);
}
int main()
{
    A &&a=getA(1);//就是修改这行代码就行
    int testValue = a.getValue();
    std::cout << "testValue: " << testValue << std::endl;
    return 0;
}

而且,右值引用无法被左值初始化,只能用右值初始化:

int a = 20;    // 左值
int&& test1= a;   // 非法:右值引用无法被左值初始化
const int&& test2= a;  // 非法:右值引用无法被左值初始化

有人的解释为:因为右值引用的目的是为了延长用来初始化对象的生命周期,对于左值,其生命周期与其作用域有关,你没有必要去延长

全部评论

相关推荐

想干测开的tomca...:让我来压力你!!!: 这份简历看着“技术词堆得满”,实则是“虚胖没干货”,槽点一抓一大把: 1. **项目描述是“技术名词报菜名”,没半分自己的实际价值** 不管是IntelliDoc还是人人探店,全是堆Redis、Elasticsearch、RAG这些时髦词,但你到底干了啥?“基于Redis Bitmap管理分片”是你写了核心逻辑还是只调用了API?“QPS提升至1500”是你独立压测优化的,还是团队成果你蹭着写?全程没“我负责XX模块”“解决了XX具体问题”,纯把技术文档里的术语扒下来凑字数,看着像“知道名词但没实际动手”的实习生抄的。 2. **短项目塞满超纲技术点,可信度直接***** IntelliDoc就干了5个月,又是RAG又是大模型流式响应又是RBAC权限,这堆活儿正经团队分工干都得小半年,你一个后端开发5个月能吃透这么多?明显是把能想到的技术全往里面塞,生怕别人知道你实际只做了个文件上传——这种“技术堆砌式造假”,面试官一眼就能看出水分。 3. **技能栏是“模糊词混子集合”,没半点硬核度** “熟悉HashMap底层”“了解JVM内存模型”——“熟悉”是能手写扩容逻辑?“了解”是能排查GC问题?全是模棱两可的词,既没对应项目里的实践,也没体现深度,等于白写;项目里用了Elasticsearch的KNN检索,技能栏里提都没提具体掌握程度,明显是“用过但不懂”的硬凑。 4. **教育背景和自我评价全是“无效信息垃圾”** GPA前10%这么好的牌,只列“Java程序设计”这种基础课,分布式、微服务这些后端核心课提都不提,白瞎了专业优势;自我评价那堆“积极认真、细心负责”,是从招聘网站抄的模板吧?没有任何和项目挂钩的具体事例,比如“解决过XX bug”“优化过XX性能”,纯废话,看完等于没看。 总结:这简历是“技术名词缝合怪+自我感动式凑数”,看着像“背了后端技术栈名词的应届生”,实则没干货、没重点、没可信度——面试官扫30秒就会丢一边,因为连“你能干嘛”都没说清楚。
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务