C++ auto类型推导注意事项

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;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值