Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
可能重复: C++0x auto 关键字多少太多了 新关键字“auto”;什么时候应该使用它来声明变量类型?
在 C++11 中,键入一个变量auto而不是int, 将使编译器自动使用正确的类型,从其初始化上下文中推断出来。这在类型很明显但写起来很无聊的情况下非常方便。是否有需要注意的陷阱,或者有人会避免使用它的原因?
auto
int
我的个人经验是 auto 对于通用代码或基于范围的 for 循环之类的东西很方便,但你可能会得到类似的东西
auto count = getCount(); if (count < 0) { // do something }
如果 getCount() 返回一个无符号数,而不是您可能期望的 (int),您甚至不会收到警告。