auto 和 auto &是不一样的

前言

什么时候用auto什么时候用auto&呢?

先看代码testauto.cpp

#include<iostream>
using namespace std;
class Type
{
public:
    Type(){cout<<"Type() this:"<<this<<endl;};
    ~Type(){cout<<"~Type() this:"<<this<<endl;}
    Type(const Type& rhs)
    {
        cout<<"Type(const Type& rhs) this:"<<this<<endl;
    }
    Type& operator=(const Type& o)
    {
        cout<<"Type& operator=(const Type& o)"<<endl;
    }
};

Type &get()
{
    static Type type;
    return type;
}

int main()
{
    {
        auto at = get(); //从输出可以看出,这里会发生拷贝构造,at的类型是Type而不是Type&
    }
    cout<<"------"<<endl;
    return 0;
}

输出结果为:

Type() this:0x557ae652b139
Type(const Type& rhs) this:0x7ffd6f32cc77
~Type() this:0x7ffd6f32cc77
------
~Type() this:0x557ae652b139

从输出结果可以看出,第27行的auto at = get();会发生拷贝构造,at的类型是Type而不是Type&。所以如果Type类的拷贝构造函数被显式delete了,或者不是public的,那么第27行就无法编译通过。如下所示:

Type(const Type& rhs)=delete;

#include<iostream>
using namespace std;
class Type
{
public:
    Type(){cout<<"Type() this:"<<this<<endl;};
    ~Type(){cout<<"~Type() this:"<<this<<endl;}
    Type(const Type& rhs)=delete;
    // {
    //     cout<<"Type(const Type& rhs) this:"<<this<<endl;
    // }
    Type& operator=(const Type& o)
    {
        cout<<"Type& operator=(const Type& o)"<<endl;
    }
};

Type &get()
{
    static Type type;
    return type;
}

int main()
{
    {
        auto at = get(); //从输出可以看出,这里会发生拷贝构造,at的类型是Type而不是Type&
    }
    cout<<"------"<<endl;
    return 0;
}

编译时候报错为:

 再看auto&

写上面第27行的auto at = get();的时候,本来想的是at会自动推导为Type&类型,但实际上却不是。如果改成auto &at = get();,就可以达到最初的目的。

#include<iostream>
using namespace std;
class Type
{
public:
    Type(){cout<<"Type() this:"<<this<<endl;};
    ~Type(){cout<<"~Type() this:"<<this<<endl;}
    Type(const Type& rhs)=delete;
    // {
    //     cout<<"Type(const Type& rhs) this:"<<this<<endl;
    // }
    Type& operator=(const Type& o)
    {
        cout<<"Type& operator=(const Type& o)"<<endl;
    }
};

Type &get()
{
    static Type type;
    return type;
}

int main()
{
    {
        auto &at = get(); 
    }
    cout<<"------"<<endl;
    return 0;
}

这次编译通过

输出结果为:

Type() this:0x56329daa6139
------
~Type() this:0x56329daa6139

结论

用auto &at = get();at不会发生拷贝构造,at是get()返回对象的引用。

用auto at = get();尽管get()函数返回的是Type的引用,还是会发生拷贝构造,at是一个新的对象,at类型是Type不是Type&

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值