百科问答小站 logo
百科问答小站 font logo



C++中,auto关键字有哪些乱用的情况?平时使用有哪些坑? 第1页

  

user avatar   frmf 网友的相关建议: 
      

乱用的话代码的可读性会变差。auto还是需要放在编码规范中的。

其实很多团队的编码规范里面都包含了auto的使用规范。google编码规范里面也有,它的原则可以参考。其中的精髓大概就是这样一段话:

The fundamental rule is: use type deduction only to make the code clearer or safer, and do not use it merely to avoid the inconvenience of writing an explicit type. When judging whether the code is clearer, keep in mind that your readers are not necessarily on your team, or familiar with your project, so types that you and your reviewer experience as unnecessary clutter will very often provide useful information to others. For example, you can assume that the return type of make_unique<Foo>() is obvious, but the return type of MyWidgetFactory() probably isn't.

它这里说的type deduction包含了auto和模板参数,仅仅只是关注auto的用法也一样是适用的。

google编码规范里面对于各种情况都列举了,定义自己的规范时可以参考。

就我个人体会,适合使用auto的情况随手能列出以下几种:

       1、for(auto it = container.begin(); it != container.end(); ++it)    for(const auto& item: container)    for(auto&& item: container) 2、auto f = [](){}; 3、auto p = new very_very_long_class_name;    auto p = std::make_shared<class_name>(...);    auto p = std::make_unique<class_name>(...);    auto p = std::make_tuple(5, 2.0f, std::string("123")); 4、auto [it, ok] = my_map.insert(...);    for(auto&& [key, value]: my_map)     




  

相关话题

  进程被操作系统加载之后,磁盘上的二进制文件可以删掉吗?如果删掉对正在运行的进程有什么影响吗? 
  为什么 C++ 能够源码级兼容C语言? 
  在这种不同操作下,对于计算机体系的不同是否会造成时间差异? 
  如何在运行时初始化静态成员变量? 
  结合深度学习的图像修复怎么实现? 
  为什么国外一些常见问答网站的地址栏中常常就给出了问题题目,相对于像国内一样使用ID来标记而言好在哪里? 
  为什么下面程序递归计算斐波那契数列java比c++要快? 
  大括号不换行的坏处有什么?为什么有人不换行? 
  晚上脑子里也想着bug,睡不好怎么办? 
  能否把高版本的libstdc++静态连接到一个只暴露纯C接口的动态库中,给低版本c++程序调用? 

前一个讨论
柯西审敛原理是证得收敛还是一致收敛?
下一个讨论
函数求导的逆运算?





© 2025-05-07 - tinynew.org. All Rights Reserved.
© 2025-05-07 - tinynew.org. 保留所有权利