auto
关键字可以自动推导数据类型,主要目的是提升代码可读性和可维护性。例如:
std::vector<int>::iterator I = my_container.begin();
// transforms to:
auto I = my_container.begin();
然而,有的情形不适合使用auto
关键字,例如:
int val = 42;
InfoStruct &I = SomeObject.getInfo();
// Should not become:
auto val = 42;
auto &I = SomeObject.getInfo();
上面的代码的可读性差。那什么情况下推荐使用auto
关键字?
Iterators
迭代器(Iterator)通常比较长,并且使用频率高,因此使用auto
比较合适。
for (std::vector<int>::iterator I = my_container.begin(),
E = my_container.end();
I != E; ++I) {
}
// becomes
for (auto I = my_container.begin(), E = my_container.end(); I != E; ++I) {
}
New
使用new
关键字创建对象实例时,对象名需要写两次,此时使用auto
比较合适。
TypeName *my_pointer = new TypeName(my_param);
// becomes
auto *my_pointer = new TypeName(my_param);
Cast
强制类型转换时,数据类型需要写两次,此时使用auto
比较合适。
TypeName *my_pointer = static_cast<TypeName>(my_param);
// becomes
auto *my_pointer = static_cast<TypeName>(my_param);
网友评论