今天旧事重提,再写一点关于c++11的事儿,注意是说明一下使用C++11使你的程序更加的简洁,更加漂亮。
说道简洁,我想最多想到的就是auto关键字的使用了。
比如之前你这样定义一个迭代器:
std::vector<std::stirng>::iterator iter = vec.begin();
但是有了auto关键字,你就可以少些很多代码:
auto iter = vec.begin();
好吧,你可能早就不耐烦了,因为你早就非常熟悉auto关键字了。
别着急看看下面的!
1使用auto推断的变量必须马上初始化
auto不能推断出下面两个变量
auto int y;
auto s;
2 auto可以推断new出来的变量
auto ptr = new auto(1);//ptr为int*类型
3 能分清下面的推断吗
int x = 1;
auto *a = &x;//a为int
auto b = &x; //b为int*
auto & c = x;//c为int
auto d = c; //d为int
const auto e = x;//e为 const int
auto f = e; //f为int
const auto& g=x; //g为const int&
auto& h=g; //h为const int&
需要说明的是:
表达式带有const时,auto推断会抛弃const,f为int,非const int
auto与引用结合,表达式带有const时,auto推断保留const属性,例如h为const int &
4 auto无法定义数组、无法推断模板参数
5 编译时,推导出一个表达式的类型,auto做不到,这时候有关键字decltype
int x = 1;
decltype(x) y = 1;//y为int类型
6 decltype与auto相比,可以保留const
const int& i = x;
decltype(i) j = Y;//j为const int &类型
7 兼揉并济,auto与decltype的结合
template<typename T>
auto func(T& val)->decltype(foo(val))
{
return foo(val);
}
原文:http://blog.csdn.net/wangshubo1989/article/details/50437463