2

Effective Modern C++(2): auto

 1 year ago
source link: https://keys961.github.io/2022/05/29/Effective-Modern-C++(2)/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

1. 优先使用auto而非显式声明

  • 摆脱冗长的类型声明,编写效率高

  • 摆脱未初始化行为,否则编译不过

  • 调用更快,例如

    • 闭包:autostd::function,后者可能存储不了闭包,从而在堆上申请内存,从而更耗空间且更慢
  • 不需要判断平台等方面的类型(例如size_t

  • 避免难以意识到的类型不匹配的错误

但是也有可能出现一些陷阱。

2. auto推导若非己愿,进行显式类型初始化

auto可能会推导错误,如:

  • T类型的左值不是简单变量,那么会推导为T&

  • 不可见的代理类,如

    • std::vector<bool>[]返回的不是bool&,而是内部的一个std::vector<bool>::reference类型

因此可以用显式类型进行初始化:

  • T v = func()

  • auto v = static_cast<T>(func())


Related Issues not found

Please contact @keys961 to initialize the comment


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK