问题描述
在C ++中11,键入一个变量 auto
而不是 int
,将让编译器自动使用正确的类型,推导出从其初始化上下文。这是超级方便的情况下,类型是明显的,但无聊写。
In C++11, Typing a variable auto
instead of, say, int
, will let the compiler automatically use the right type, deduced from its initialization context. This comes super handy in situations where the type is obvious but boring to write. Are there pitfalls to be aware of, or reasons why someone would avoid using that?
推荐答案
我的个人经验是汽车是方便的通用代码或基于范围的for循环,但你可能会得到像
My personal experience is auto is handy for generic code, or things like range-based for loop, but you might get something like
auto count = getCount();
if (count < 0) {
// do something
}
$ b b
如果getCount()返回一个无符号数,而不是你期望的(int),你甚至不会得到警告。
If getCount() returns an unsigned number, instead of what you might be expecting (int), you won't even get a warning.
这篇关于是C ++ 11自动类型危险吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!