百科问答小站 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)     




  

相关话题

  公民身份号码有可能是素数吗? 
  大型项目中面向过程思想 vs 面向对象思想,哪种开发效率更高? 
  为什么编程更关注内存而很少关注CPU? 
  C++ 运动完上一个函数到下一个函数时,上一个函数里的变量值(结构体变量)为什么没保留住,变成零了? 
  在计算机科学领域,为何不使用拼音代替英文做为关键字? 
  c++ 程序运行时异常处理,怎么定位到出错代码行? 
  你是因为什么而喜欢上编程的? 
  有没有一段代码,让你为人类的智慧击节叫好? 
  同是主流操作系统,为什么macOS没有盗版系统而Windows到处是盗版? 
  CSS的样式表 内联外部和内部优先级? 

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





© 2024-06-29 - tinynew.org. All Rights Reserved.
© 2024-06-29 - tinynew.org. 保留所有权利