使用auto关键字的例子:
// Iterate through the param info and seach for the names from the incoming (TestModel) parameter set.
// If the name does not exist in the model, then set param with default value
for( auto it1 = tpi->begin(); it1!=tpi->end(); ++it1 ) // SUITEK_CTestClassInfo::TestParameterInfo
{
auto it2 = test->parameters.find(it1->first); // TestParameters
bool exists = (it2 != test->parameters.end());
switch( it1->second.dataType)
{
case SUITEK_STRING:
{
static const char * EMPTY_STR = "";
// param value
void ** ppdst = (void**)((unsigned long)kTest + it1->second.offset);
const std::string & val = exists ? it2->second.parameterValue : it1->second.defaultVal;
*ppdst = val.empty() ? (void*)EMPTY_STR : (void**)&(val[0]);
if(it1->second.offsetUpperLimit) // upper limit
{
void ** ppul = (void**)((unsigned long)kTest + it1->second.offsetUpperLimit);
const std::string & ul = exists ? it2->second.upperlimit : it1->second.upperLimitVal;
*ppul = val.empty() ? (void*)EMPTY_STR : (void**)&(val[0]);
}
if(it1->second.offsetLowerLimit) // lower limit
{
void ** ppll = (void**)((unsigned long)kTest + it1->second.offsetLowerLimit);
const std::string & ll = exists ? it2->second.lowerlimit : it1->second.lowerLimitVal;
*ppll = val.empty() ? (void*)EMPTY_STR : (void**)&(val[0]);
}
break;
}
// other case, etc ..............................
}
Bjarne Stroustrup 在他的 C++0x FAQ 里这样提到 auto: "auto 的旧有的意思 ("这是一个局部变量") 是冗余的未被使用的. 几个委员会成员搜索数百万行代码,发现只有少数的使用 - 其中大多数用在测试套件中,或者看起来是bug。所以我认为编译器不会迫于标准实现 auto 的旧有的含义。"
auto 关键字在第一代C编译器中引入,用于指定本地函数变量,但编译器几乎立即变得足够聪明而不再需要它,今天很少能看到使用它的老的代码 - 这就是为什么C++ 0X选择回收它而不是引入一个会导致可移植性问题的新的关键字。C++ 0X的 auto 关键字的使用目的是,允许编译器推断出变量的类型,例如,像下面这样写code是可行的:
vector <int> v;
auto it = v.begin():
编译器会知道 v.begin() 必须返回 vector<int>::iterator
于是就可以创建这种类型的变量, 从而可以省掉 typedef 或少敲键盘。
auto 在过去是用于指定一个局部变量,而现代编译器如 VS2010 C++ 赋予它新的含义。
【翻译自 MSDN】 auto
关键字是一个声明指示符。 然而 C++ 为这一关键字定义了原始的和修订后的含义. 在 Visual C++ 2010 之前, auto
关键字在 automatic 存储类中声明了一个变量,就是说是一个具有局部生命期的变量. 从 Visual C++ 2010 开始, auto
关键字用于声明一个变量,它的类型由初始化表达式推断出来。编译器的 /Zc:auto[-] 选项控制 auto
关键字的含义。
----------------------------------
简而言之,现在用 auto 仅仅是为了代替数据类型,因为编译器自己会推断出来,从而简化code。