auto只能推导出数据的不加const,不加引用(&)的数据类型
int ia = 12;
auto aa1 = ia; // 此时aa的类型是int,相当于int aa = ia;
int& ra = ia;
auto aa2 = ra; // 我们希望aa2的类型是int&, 实际上aa2的类型是int。如果是class或者struct类型型,这里会调用copy构造函数。aa2使用独立内存
const int& cri = ia;
auto aa3 = cri; // 我们希望aa2的类型是const int&, 实际上aa2的类型是int。如果是class或者struct类型型,这里会调用copy构造函数。aa2使用独立内存
C++11里面的decltype可以识别const和引用
class testAuto
{
public:
testAuto()
{
cout << "constructor testAtuto" << endl;
}
testAuto(const testAuto& other)
{
cout << "copy constructor testAuto" << endl;
}
testAuto& operator=(const testAuto& other)
{
cout << "assign constrator testAuto" << endl;
return *this;
}
};
int main()
{
testAuto test;
cout << "**********1***********" << endl;
const testAuto ctest = test;
cout << "**********2***********" << endl;
const testAuto& rtest = ctest;
cout << "**********3***********" << endl;
auto atest = rtest; // atest 实际类型testAuto
cout << "**********4***********" << endl;
decltype(rtest) dstr = ctest; // dstr 类型为const testAuto&
cout << "**********5***********" << endl;
decltype(atest) adtest = rtest;
cout << "**********6***********" << endl;
vector<int> vint(10, 1);
for (auto& val:vint)
{
val++;
}
for (auto val:vint)
{
cout << val << ",";
}
cout << endl;
}