C ++ 11 auto关键字多少钱? [英] How much is too much with C++11 auto keyword?

查看:118
本文介绍了C ++ 11 auto关键字多少钱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用C ++ 11标准中对于复杂模板类型提供的新的 auto 关键字,这是我相信的。但我也使用它的东西像:

I've been using the new auto keyword available in the C++11 standard for complicated templated types which is what I believe it was designed for. But I'm also using it for things like:

auto foo = std::make_shared<Foo>();

更怀疑的是:

auto foo = bla(); // where bla() return a shared_ptr<Foo>

我没有看到太多关于这个话题的讨论。看来auto可以被过度使用,因为类型通常是一种形式的文档和健全检查。使用 auto 在哪里绘制线条?这个新功能的推荐用例是什么?

I haven't seen much discussion on this topic. It seems that auto could be overused, since a type is often a form of documentation and sanity checks. Where do you draw the line in using auto and what are the recommended use cases for this new feature?

澄清:我不是要求一个哲学意见;我要求标准委员会对该关键字的预期用途,可能会对实际使用的意图如何实现。

To clarify: I'm not asking for a philosophical opinion; I'm asking for the intended use of this keyword by the standard committee, possibly with comments on how that intended use is realized in practice.

注意:这个问题被移动到SE.Programmers,然后回到Stack Overflow。有关此问题的讨论,请参阅此元问题

推荐答案

我认为应该使用 auto 关键字,当很难说如何写类型视线,但是表达式右侧的类型是显而易见的。例如,使用:

I think that one should use the auto keyword whenever it's hard to say how to write the type at first sight, but the type of the right hand side of an expression is obvious. For example, using:

my_multi_type::nth_index<2>::type::key_type::composite_key_type::\
key_extractor_tuple::tail_type::head_type::result_type

code> boost :: multi_index ,即使你知道它是 int 。你不能写 int ,因为它可以在将来更改。在这种情况下,我会写 auto

to get the composite key type in boost::multi_index, even though you know that it is int. You can't just write int because it could be changed in the future. I would write auto in this case.

所以如果 auto 关键字在特定情况下提高可读性,然后使用它。当向读者显示 auto 代表什么类型时,您可以写 auto

So if the auto keyword improves readability in a particular case then use it. You can write auto when it is obvious to the reader what type auto represents.

以下是一些示例:

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 ++ 11 auto关键字多少钱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆