编程语言
首页 > 编程语言> > 1_auto类型推导(深入应用C++11:代码优化与工程级应用)

1_auto类型推导(深入应用C++11:代码优化与工程级应用)

作者:互联网

1. auto回顾

  在深入学习auto前,本人已经了解了auto的基本用法,对于简单类型推导能够清晰理解.如:

int i = 0;
auto ii = 1;    // auto被推导为int
auto iii = i;   // auto被推导为int

  本次学习是为了加深细节理解,如:auto 与指针\引用\cv限定符一起使用时的推导结果.

  回顾下简单类型的推导及使用auto时需要注意哪些.

int int_type = 1;               //int       auto被推导为int
float float_type = 1.0;         //float     auto被推导为float
const int const_int_type = 1;   //int const auto被推导为int
auto auto_int = 1;              //int       auto被推导为int
auto auto_double = 1.0;         //double    auto被推导为double

auto x= 5;                      //int       auto被推导为int
auto pi = new auto(1);          //int*      auto被推导为int*
const auto *v = &x, u=6;        //v:int const *    auto 被推导为 int
                                //u:int const      auto 被推导为 int
static auto y = 0.0;            //double           auto被推导为double
auto int r;         // error:two or more data types in declaration of 'r' 
int int r;          // error:two or more data types in declaration of 'r'
auto s;             // error:declaration of 'auto s' has no initializer

需要注意的是:

const auto *v = &x, u=6;
//在推导的时候u必须赋值,且所赋的值不能让auto推导产生二义性,否则无法通过编译
/**u 必须要赋值,否则就等价 const auto u;// error
    * 如:const auto *v = &x, u;
    * error: declaration of variable 'u' with deduced type 'const auto' requires an initializer
    */
/**并且u的初始化不能是编译器推导产生二义性,否则编译失败.
    * 如:const auto *v = &x, u =6.0;
    * error: 'auto' deduced as 'int' in declaration of 'v' and deduced as 'double' in declaration of 'u'
    */

  由上面的例子可以看出来,auto并不能代表一个实际的类型声明(如s的编译错误),只是一个类型声明的"占位符".

  使用auto声明的变量必须马上初始化,以上编译器推断出它的实际类型,并在编译时将auto占位符替换为真正的类型.

2. auto推导规则

int x = 0;
auto * a = &x;          // int* auto被推导为int
auto   b = &x;          // int* auto被推导为int*
auto & c = x;           // int& auto被推导为int
auto   d = c;           // int  auto被推导为int

const auto e = x;       // int const   auto被推导为int
auto   f = e;           // int         auto被推导为int
const auto & g = x;     // int const & auto被推导为int
auto & h = g;           // int const & auto被推导为int const

const auto * gg = &x;   // int const * auto被推导为int
auto * hh = gg;         // int const * auto被推导为int const

  由上面的例子可以看出:

通过上面一系列示例, 可以得到下面两条规则:

  1. 当不声明为指针或引用时, auto的推导结果和初始化表达式抛弃引用和cv限定符后类型一致.
  2. 当声明为指针或引用时, auto的推导结果将保持初始化表达式的cv属性.

标签:11,const,推导,int,auto,代码优化,declaration,类型
来源: https://www.cnblogs.com/dog-pi/p/16519517.html