C++ auto 变量及其类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13583172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
auto variable and its type
提问by Yakov
I found in a post how to delete elements from a container using an iterator. While iterating:
我在一篇文章中找到了如何使用迭代器从容器中删除元素。迭代时:
for(auto it = translationEvents.begin(); it != translationEvents.end();)
{
auto next = it;
++next; // get the next element
it->second(this); // process (and maybe delete) the current element
it = next; // skip to the next element
}
Why is auto
used without the type in auto next = it;
?
为什么在auto
没有输入的情况下使用auto next = it;
?
I use VS10,not C++11 !
我使用 VS10,而不是 C++11!
回答by Joseph Mansfield
auto
has a different meaning in C++11 than it did before. In earlier standards, auto
was a storage specifier for automatic storage duration - the typical storage an object has where it is destroyed at the end of its scope. In C++11, the auto
keyword is used for type deduction of variables. The type of the variable is deduced from the expression being used to initialise it, much in the same way template parameters may be deduced from the types of a template function's arguments.
auto
在 C++11 中的含义与以前不同。在早期的标准中,auto
是自动存储持续时间的存储说明符 - 对象在其范围结束时被销毁的典型存储。在 C++11 中,auto
关键字用于变量的类型推导。变量的类型是从用于初始化它的表达式中推导出来的,这与可以从模板函数的参数类型中推导出模板参数的方式非常相似。
This type deduction is useful when typing out ugly long types has no benefit. Often, the type is obvious from the initialiser. It is also useful for variables whose type might depend on which instantiation of a template it appears in.
当输入丑陋的长类型没有任何好处时,这种类型推导很有用。通常,类型在初始化程序中很明显。对于类型可能取决于它出现在模板的哪个实例化中的变量,它也很有用。
Many C++11 features are supported by default in VC10 and auto
is one of them.
VC10 中默认支持许多 C++11 功能,并且auto
是其中之一。
回答by Chris
It is a short-hand in newer versions of C++ that allows us to avoid the clunky iterator notation, since the compiler is able to infer what the actual type is supposed to be.
它是较新版本的 C++ 中的简写,它允许我们避免笨重的迭代器符号,因为编译器能够推断实际类型应该是什么。
回答by lucas clemente
It's called Type Inference, see also this questionfor details. New in C++11, and intended to simplify many long and unnecessary codes, especially for iterators and function bindings.
它称为Type Inference,有关详细信息,另请参阅此问题。C++11 中的新增功能,旨在简化许多冗长且不必要的代码,尤其是迭代器和函数绑定。
回答by Olaf Dietsche
This is called type inference. The type of the auto variable is deduced by the type of the initializer.
这称为类型推断。auto 变量的类型由初始化器的类型推导出来。
E.g., this reduces the amount to type for large and complicated template types.
例如,这减少了大型复杂模板类型的输入量。