我一直在为复杂的模板化类型使用 C++11 标准中可用的新 auto
关键字,我相信它就是为此而设计的。但我也将它用于以下用途:
auto foo = std::make_shared<Foo>();
更怀疑的是:
auto foo = bla(); // where bla() return a shared_ptr<Foo>
我还没有看到很多关于这个话题的讨论。似乎 auto
可能被过度使用,因为类型通常是一种文档和健全性检查的形式。您在使用 auto
方面划清界限,这个新功能的推荐用例是什么?
澄清一下:我不是在征求哲学意见;我正在询问标准委员会对这个关键字的预期用途,并可能对在实践中如何实现预期用途发表评论。
最佳答案
我认为当乍一看很难说如何写类型时,应该使用 auto
关键字,但是表达式右侧的类型是显而易见的。例如,使用:
my_multi_type::nth_index<2>::type::key_type::composite_key_type::
key_extractor_tuple::tail_type::head_type::result_type
获取 boost::multi_index
中的复合键类型,即使您知道它是 int
。你不能只写 int
因为它可能在未来被改变。在这种情况下,我会写 auto
。
因此,如果 auto
关键字在特定情况下提高了可读性,那么就使用它。当读者很清楚 auto
代表什么类型时,您可以编写 auto
。
这里有一些例子:
auto foo = std::make_shared<Foo>(); // obvious
auto foo = bla(); // unclear. don't know which type `foo` has
const size_t max_size = 100;
for ( auto x = max_size; x > 0; --x ) // unclear. could lead to the errors
// since max_size is unsigned
std::vector<some_class> v;
for ( auto it = v.begin(); it != v.end(); ++it )
// ok, since I know that `it` has an iterator type
// (don't really care which one in this context)
关于c++ - C++ 11 auto关键字多少太多了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25230832/