是否有任何理由在 C++03 中使用“auto”关键字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1046477/
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
Is there any reason to use the 'auto' keyword in C++03?
提问by Carson Myers
Notethis question was originally posted in 2009, before C++11 was ratified and before the meaning of the
auto
keyword was drastically changed. The answers provided pertain onlyto the C++03 meaning ofauto
-- that being a storage class specified -- and not the C++11 meaning ofauto
-- that being automatic type deduction. If you are looking for advice about when to use the C++11auto
, this question is not relevant to that question.
请注意,这个问题最初是在 2009 年发布的,在 C++11 被批准之前,并且在
auto
关键字的含义发生巨大变化之前。提供的答案仅适用于 C++03 的含义auto
——即指定的存储类——而不是 C++11 的含义auto
——即自动类型推导。如果您正在寻找有关何时使用 C++11 的建议auto
,则此问题与该问题无关。
For the longest time I thought there was no reason to use the static
keyword in C, because variables declared outside of block-scope were implicitly global. Then I discovered that declaring a variable as static
within block-scope would give it permanent duration, and declaring it outside of block-scope (in program-scope) would give it file-scope (can only be accessed in that compilation unit).
在很长一段时间里,我认为没有理由static
在 C 中使用关键字,因为在块范围之外声明的变量是隐式全局的。然后我发现static
在块范围内声明一个变量会赋予它永久的持续时间,而在块范围之外(在程序范围内)声明它会给它文件范围(只能在那个编译单元中访问)。
So this leaves me with only one keyword that I (maybe) don't yet fully understand: The auto
keyword. Is there some other meaning to it other than 'local variable?' Anything it does that isn't implicitly done for you wherever you may want to use it? How does an auto
variable behave in program scope? What of a static auto
variable in file-scope? Does this keyword have any purpose other than just existing for completeness?
所以这让我只剩下一个我(可能)还没有完全理解的auto
关键字:关键字。除了“局部变量”之外,它还有其他含义吗?无论您想在何处使用它,它所做的任何事情都不会隐含地为您完成?auto
变量在程序范围内的行为如何?static auto
文件范围内的变量是什么?除了为了完整性而存在之外,这个关键字还有其他用途吗?
采纳答案by Johannes Schaub - litb
auto
is a storage class specifier, static
, register
and extern
too. You can only use one of these four in a declaration.
auto
是一个存储类说明,static
,register
和extern
也。您只能在声明中使用这四个中的一个。
Local variables (without static
) have automatic storage duration, which means they live from the start of their definition until the end of their block. Putting auto in front of them is redundant since that is the default anyway.
局部变量(没有static
)具有自动存储持续时间,这意味着它们从定义的开始一直存在到它们的块结束。将 auto 放在它们前面是多余的,因为无论如何这是默认设置。
I don't know of any reason to use it in C++. In old C versions that have the implicit int rule, you could use it to declare a variable, like in:
我不知道有什么理由在 C++ 中使用它。在具有隐式 int 规则的旧 C 版本中,您可以使用它来声明一个变量,例如:
int main(void) { auto i = 1; }
To make it valid syntax or disambiguate from an assignment expression in case i
is in scope. But this doesn't work in C++ anyway (you have to specify a type). Funny enough, the C++ Standard writes:
使其有效语法或消除赋值表达式的歧义,以防万一i
在范围内。但这无论如何在 C++ 中不起作用(您必须指定一个类型)。有趣的是,C++ 标准写道:
An object declared without a storage-class-specifier at block scope or declared as a function parameter has automatic storage duration by default. [Note: hence, the auto specifier is almost always redundant and not often used; one use of auto is to distinguish a declaration-statement from an expression-statement (6.8) explicitly. — end note]
默认情况下,在块范围内未使用存储类说明符声明或声明为函数参数的对象具有自动存储持续时间。[注意:因此,自动说明符几乎总是多余的并且不经常使用;auto 的一种用途是明确区分声明语句和表达式语句 (6.8)。— 尾注]
which refers to the following scenario, which could be either a cast of a
to int
or the declaration of a variable a
of type int
having redundant parentheses around a
. It is always taken to be a declaration, so auto
wouldn't add anything useful here, but would for the human, instead. But then again, the human would be better off removing the redundant parentheses around a
, I would say:
它指的是以下情形,这可能是任一的流延a
到int
或一个变量的声明a
类型的int
具有围绕冗余括号a
。它总是被认为是一个声明,所以auto
不会在这里添加任何有用的东西,而是对人类来说。但是话又说回来,人类最好去掉 周围的多余括号a
,我会说:
int(a);
With the new meaning of auto
arriving with C++0x, I would discourage using it with C++03's meaning in code.
有了auto
C++0x的新含义,我不鼓励在代码中使用 C++03 的含义。
回答by std''OrgnlDave
In C++11, auto
has new meaning: it allows you to automatically deduce the type of a variable.
在 C++11 中,auto
有了新的含义:它允许您自动推断变量的类型。
Why is that ever useful? Let's consider a basic example:
为什么这总是有用的?让我们考虑一个基本的例子:
std::list<int> a;
// fill in a
for (auto it = a.begin(); it != a.end(); ++it) {
// Do stuff here
}
The auto
there creates an iterator of type std::list<int>::iterator
.
在auto
那里创建类型的迭代器std::list<int>::iterator
。
This can make some seriously complex code much easier to read.
这可以使一些非常复杂的代码更容易阅读。
Another example:
另一个例子:
int x, y;
auto f = [&]{ x += y; };
f();
f();
There, the auto
deduced the type required to store a lambda expression in a variable.
Wikipedia has good coverage on the subject.
回答by Daniel Earwicker
The auto keyword has no purpose at the moment. You're exactly right that it just restates the default storage class of a local variable, the really useful alternative being static
.
auto 关键字目前没有任何用途。您完全正确,它只是重述了局部变量的默认存储类,真正有用的替代方法是static
.
It has a brand new meaningin C++0x. That gives you some idea of just how useless it was!
它在 C++0x 中有一个全新的含义。这让你知道它是多么无用!
回答by qrdl
回答by T.E.D.
"auto" supposedly tells the compiler to decide for itself where to put the variable (memory or register). Its analog is "register", which supposedly tells the compiler to try to keep it in a register. Modern compilers ignore both, so you should too.
“auto”据说是告诉编译器自己决定把变量放在哪里(内存或寄存器)。它的模拟是“寄存器”,据说它告诉编译器尝试将它保存在寄存器中。现代编译器忽略了两者,所以你也应该这样做。
回答by luke
I use this keyword to explicitly document when it is critical for function, that the variable be placed on the stack, for stack-based processors. This function can be required when modifying the stack prior to returning from a function (or interrupt service routine). In this case I declare:
对于基于堆栈的处理器,我使用此关键字来明确记录何时对功能至关重要,即将变量放置在堆栈上。在从函数(或中断服务例程)返回之前修改堆栈时可能需要此函数。在这种情况下,我声明:
auto unsigned int auiStack[1]; //variable must be on stack
And then I access outside the variable:
然后我在变量之外访问:
#define OFFSET_TO_RETURN_ADDRESS 8 //depends on compiler operation and current automatics
auiStack[OFFSET_TO_RETURN_ADDRESS] = alternate_return_address;
So the auto
keyword helps document the intent.
所以auto
关键字有助于记录意图。
回答by wesley.mesquita
According to Stroustrup, in "The C Programming Language" (4th Edition, covering C 11), the use of 'auto' has the following major reasons (section 2.2.2) (Stroustrup words are quoted):
根据 Stroustrup 的说法,在《The C Programming Language》(第 4 版,涵盖 C 11)中,使用“auto”有以下主要原因(第 2.2.2 节)(引用 Stroustrup 的话):
1)
1)
The definition is in a large scope where we want to make the type clearly visible to readers of our code.
定义在一个很大的范围内,我们希望让代码的读者清楚地看到类型。
With 'auto' and its necessary initializer we can know the variable's type in a glance!
使用 'auto' 及其必要的初始化程序,我们可以一目了然地知道变量的类型!
2)
2)
We want to be explicit about variable's range or precision (e.g., double rather than float)
我们想要明确变量的范围或精度(例如,double 而不是 float)
In my opinion a case that fits here, is something like this:
在我看来,一个适合这里的案例是这样的:
double square(double d)
{
return d*d;
}
int square(int d)
{
return d*d;
}
auto a1 = square(3);
cout << a1 << endl;
a1 = square(3.3);
cout << a1 << endl;
3)
3)
Using 'auto' we avoid redundancy and writing long type names.
使用 'auto' 我们避免冗余和编写长类型名称。
Imagine some long type name from a templatized iterator:
想象一下来自模板化迭代器的一些长类型名称:
(code from section 6.3.6.1)
(来自第 6.3.6.1 节的代码)
template<class T> void f1(vector<T>& arg) {
for (typename vector<T>::iterator p = arg.begin(); p != arg.end(); p)
*p = 7;
for (auto p = arg.begin(); p != arg.end(); p)
*p = 7;
}
回答by chaz
In old compiler, auto was one way to declare a local variable at all. You can't declare local variables in old compilers like Turbo C without the auto keyword or some such.
在旧的编译器中, auto 是一种声明局部变量的方法。如果没有 auto 关键字或类似关键字,您不能在像 Turbo C 这样的旧编译器中声明局部变量。
回答by Sabuncu
The new meaning of the auto keyword in C++0x is described very nicely by Microsoft's Stephan T. Lavavej in a freely viewable/downloadable video lecture on STL found at MSDN's Channel 9 site here.
C ++ 0x中自动关键字的新含义在自由观看/下载的视频讲座非常漂亮的描述微软的斯蒂芬T. Lavavej对STL在MSDN的第9频道网站上发现这里。
The lecture is worth viewing in its entirety, but the part about the auto keyword is at about the 29th minute mark (approximately).
整个讲座值得一看,但关于 auto 关键字的部分大约在第 29 分钟(大约)。
回答by Jirka Hanika
Is there some other meaning to 'auto' other than 'local variable?'
除了“局部变量”之外,“自动”还有其他含义吗?
Not in C++03.
不在 C++03 中。
Anything it does that isn't implicitly done for you wherever you may want to use it?
无论您想在何处使用它,它所做的任何事情都不会隐含地为您完成?
Nothing whatsoever, in C++03.
什么都没有,在 C++03 中。
How does an auto variable behave in program scope? What of a static auto variable in file-scope?
自动变量在程序范围内的行为如何?文件范围内的静态自动变量是什么?
Keyword not allowed outside of a function/method body.
不允许在函数/方法主体之外使用关键字。
Does this keyword have any purpose [in C++03] other than just existing for completeness?
除了为了完整性而存在之外,这个关键字是否有任何目的 [在 C++03 中]?
Surprisingly, yes. C++ design criteria included a high degree of backward compatibility with C. C had this keyword and there was no real reason to ban it or redefine its meaning in C++. So, the purpose was one less incompatibility with C.
令人惊讶的是,是的。C++ 设计标准包括与 C 的高度向后兼容性。C 有这个关键字,并且没有真正的理由禁止它或在 C++ 中重新定义它的含义。因此,目的是减少与 C 的不兼容性。
Does this keyword have any purpose in C other than just existing for completeness?
除了为了完整性而存在之外,这个关键字在 C 中是否还有其他用途?
I learned one only recently: ease of porting of ancient programs from B. C evolved from a language called B whose syntax was quite similar to that of C. However, B had no types whatsoever. The only way to declare a variable in B was to specify its storage type (auto
or extern
). Like this:
我最近才了解到一个:易于移植 B 的古老程序。C 是从一种称为 B 的语言演变而来的,它的语法与 C 的语法非常相似。但是,B 没有任何类型。在 B 中声明变量的唯一方法是指定其存储类型(auto
或extern
)。像这样:
auto i;
自动我;
This syntax still works in C and is equivalent to
此语法在 C 中仍然有效,等效于
int i;
国际我;
because in C, the storage class defaults to auto
, and the type defaults to int
. I guess that every single program that originated in B and was ported to C was literally full of auto
variables at that time.
因为在 C 中,存储类默认为auto
,类型默认为int
。我猜想每个源自 B 并移植到 C 的程序当时都充满了auto
变量。
C++03 no longer allows the C style implicit int, but it preserved the no-longer-exactly-useful auto
keyword because unlike the implicit int, it wasn't known to cause any trouble in the syntax of C.
C++03 不再允许 C 风格的隐式 int,但它保留了不再完全有用的auto
关键字,因为与隐式 int 不同,它不会在 C 的语法中造成任何问题。