C++11 auto自动类型推导

1. auto类型推导

下面是auto的使用举例:

  1.  

    auto x =5; //正确,x是int类型auto pi = new auto(1); //正确,批是int*const auto* v = &x, u = 6; //正确,v是const int*类型,u是const intstatic auto y = 0.0; //正确,y是double类型auto int r; //错误,auto不再表示存储类型的指示符auto s; //错误,auto无法推导出s的类型(必须马上初始化)

     

auto并不能代表一个实际的类型声明(上面s编译错误),只是一个类型声明的“占位符”。使用auto声明的变量必须马上初始化,以让编译器推断出它的类型,并且在编译时将auto占位符替换为真正的类型。

2. auto类型推导规则

  1.  

    int x = 0;auto *a = &x; //a->int*,auto被推导为intauto b = &x; //b->int*,auto被推导为int*auto &c = x; //c->int&,auto被推导为intauto d = c; //d->int, auto被推导为intconst auto e = x; //e->const intauto f = e; //f->intconst auto& g = x; /