在控制结构中定义变量
根据该标准,在控制结构中声明变量与在其他地方声明变量之间的行为有什么区别?我似乎找不到任何提及它的地方。
如果我指的不清楚,这里有一个示例:
if (std::shared_ptr<Object> obj = objWeakPtr.lock())
如您所见,我在 if 块中声明并初始化一个局部变量 obj
。
另外,是否有任何技术原因说明为什么此语法在代替条件使用时没有给出任何特殊行为?例如,添加一组额外的括号会导致编译器错误;这也可以防止变量与其他条件链接。
// Extra brackets, won't compile.
if ((std::shared_ptr<Object> obj = objWeakPtr.lock()))
// If the above were valid, something like this could be desirable.
if ((std::shared_ptr<Object> obj = objWeakPtr.lock()) && obj->someCondition())
According to the standard, what is the difference in behavior between declaring variables in control structures versus declaring variables elsewhere? I can't seem to find any mention of it.
If what I'm referring to isn't clear, here's an example:
if (std::shared_ptr<Object> obj = objWeakPtr.lock())
As you can see, I'm declaring and initializing a local variable, obj
, in the if block.
Also, is there any technical reason as to why this syntax isn't given any special behavior when used in place of a conditional? For example, adding an additional set of brackets results in a compiler error; this also prevents the variable from being chained with other conditions.
// Extra brackets, won't compile.
if ((std::shared_ptr<Object> obj = objWeakPtr.lock()))
// If the above were valid, something like this could be desirable.
if ((std::shared_ptr<Object> obj = objWeakPtr.lock()) && obj->someCondition())
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
控制结构引入内的声明与其他地方的声明没有什么不同。这就是为什么你找不到任何差异。
6.4/3 确实为此描述了一些特定的语义,但并不令人意外:
if
条件可以包含声明性语句或表达式。任何表达式都不能包含声明性语句,因此也不能混合它们。这一切都源于语法产生。
Declarations inside control structure introductions are no different that declarations elsewhere. That's why you can't find any differences.
6.4/3 does describe some specific semantics for this, but there are no surprises:
An
if
condition can contain either a declarative statement or an expression. No expression may contain a declarative statement, so you can't mix them either.It all just follows from the grammar productions.
在条件中声明和初始化变量与在其他地方声明变量的区别在于,变量用作条件,并且位于 if 条件语句内的范围内,但超出该条件之外的范围。另外,在 if 条件内重新声明变量是不合法的。所以
但是:
The difference from declaring and initializing a variable in the condition and declaring it elsewhere is that the variable is used as the condition, and is in scope inside the if's conditional statement, but out of scope outside that condition. Also, it's not legal to re-declare the variable inside the if condition. So
but: