我一直在使用c++ 11标准中提供的新的auto关键字来处理复杂的模板类型,我相信它就是为这个目的设计的。但我也用它来做以下事情:
auto foo = std::make_shared<Foo>();
更令人怀疑的是:
auto foo = bla(); // where bla() return a shared_ptr<Foo>
我还没有看到很多关于这个话题的讨论。auto似乎被滥用了,因为类型通常是一种文档和完整性检查的形式。你在使用auto方面的界限在哪里,这个新功能的推荐用例是什么?
澄清一下:我并不是在寻求哲学观点;我要求标准委员会对这个关键字的预期使用,可能还会对如何在实践中实现预期使用发表评论。
我使用auto的一个痛苦经历是在lambda表达式中使用它:
auto i = []() { return 0; };
cout<<"i = "<<i<<endl; // output: 1 !!!
实际上,这里i被解析为int(*)()的函数指针。这只是一个简单的cout,但是想象一下,当它与template一起使用时,会导致什么样的编译/运行时错误。
你应该避免使用这样的表达式,并设置一个合适的返回类型(或受控的decltype())
上述例子的正确用法是:
auto i = []() { return 0; }(); // and now i contains the result of calling the lambda
我使用auto没有任何限制,没有遇到任何问题。有时我甚至把它用于简单的类型,如int。这使得c++对我来说是一种更高级别的语言,并且允许在c++中像在python中一样声明变量。在写完python代码之后,我有时甚至会写例如。
auto i = MyClass();
而不是
MyClass i;
这是我认为auto关键字滥用的一种情况。
Often I don't mind what is the exact type of the object, I'm more interested in its fonctionality, and as function names generally say something about the objects they return, auto does not hurt: in e.g. auto s = mycollection.size(), I can guess that s will be a kind of integer, and in the rare case where I care about the exact type, let's check the function prototype then (I mean, I prefer to have to check when I need the info, rather than a priori when code is written, just in case it would be usefull someday, as in int_type s = mycollection.size()).
关于这个例子,从公认的答案:
for ( auto x = max_size; x > 0; --x )
在我的代码中,在这种情况下我仍然使用auto,如果我想让x是unsigned,那么我使用一个实用函数,命名为say make_unsigned,这清楚地表达了我的担忧:
for ( auto x = make_unsigned(max_size); x > 0; --x )
免责声明:我只是描述我的使用,我没有能力给出建议!
在c++和超越2012的Ask Us Anything小组中,Andrei Alexandrescu、Scott Meyers和Herb Sutter就何时使用和不使用auto进行了一次精彩的交流。跳到25:03分钟进行4分钟的讨论。这三位演讲者都给出了很好的观点,应该记住什么时候不使用auto。
我非常鼓励人们得出自己的结论,但我的结论是在任何地方都要使用auto,除非:
这会影响可读性
关心自动类型转换(例如,从构造函数,赋值,模板中间类型,整数宽度之间的隐式转换)
自由地使用explicit有助于减少对后者的关注,这有助于最大限度地减少前者成为问题的时间。
换句话说,Herb说,“如果你不做X, Y和Z,用auto。了解X, Y和Z是什么,然后在其他地方使用auto。”
什么汽车?
它告诉编译器根据变量的初始值推断(确定)变量的数据类型。它使用类型演绎。
auto应该用在哪里?
当你对变量的类型不感兴趣时
想要使用它。
当你想要避免非常长和丑陋的typename。
当你不确定自己的类型时。
当你不想在你的代码中看到未初始化的变量。
Auto强制你初始化一个变量,因此你不能忘记做
那
当它不应该使用或缺点的自动
参考它的功能,auto可能会错误地推断类型,1
这种情况是
Std::vector<bool> vec(10,0);
Auto x = vec[2];
Bool y = vec[2];
Std::cout << typeid(x).name() << "\n";
Std::cout << typeid(y).name() << "\n";
g++ 10.2上的输出令人惊讶:
St14_Bit_reference
b
如果你想让你的代码可读&,不应该使用它
对其他人来说是可以理解的。它隐藏了数据类型的可见性
来自读者。