前言
什么时候用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&