C++短路评估
也许我错过了一些相当简单的东西,但是当我取消引用指针时,即使我检查表达式最开头的点,我也会崩溃。
if( var1 &&
bool1 || bool2 &&
var1->DoSomething() )
{
}
var1 是一个空指针,但 Var1->Dosomething() 仍在被调用。我的理解是 &&和|| C++ 中的运算符是短路的,因此如果 var1 为 null,那么它就会从一开始就终止。还是我还缺少其他东西?
Maybe I am missing something rather simple, but I am getting a crash when I dereference a pointer even though I check the point at the very beginning of the expression.
if( var1 &&
bool1 || bool2 &&
var1->DoSomething() )
{
}
var1 is a null pointer, but Var1->Dosomething() is still being called. My understanding is that the && and the || operator in C++ are short circuit so if var1 was null then it would just terminate at the very beginning. Or is there something else I am missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
运算符优先级是这里的关键。由于
&&
的优先级高于||
,因此您的表达式等效于So,因为
var1
的计算结果为 false,bool1
不会被计算,并且(var1 && bool1)
产生 false,因此(bool2 && var1->DoSomething())
必须是评价。如果bool2
恰好为 true,则var1->DoSomething()
也将被求值,从而导致未定义的行为。只需添加一些括号(针对您需要的特定表达式树)就可以了。
Operator precedence is the key here. Because
&&
has higher precedence than||
, your expression is equivalent toSo, since
var1
evaluates to false,bool1
is not evaluated and(var1 && bool1)
yields false, therefore(bool2 && var1->DoSomething())
has to be evaluated. And ifbool2
happens to be true, thenvar1->DoSomething()
will also be evaluated, resulting in undefined behavior.Just add some parentheses (for the specific expression tree that you require) and you'll be fine.
由于
&&
的优先级高于||
,因此您的表达式将被解析为(var1 && bool1) || (bool2 && var1->DoSomething())
。现在,由于var1
是空指针,短路求值意味着bool1
不求值,并且||
的左侧求值为 false 。因此,要找出表达式的值,必须对右侧进行求值(即短路求值不会在这里起作用!)。||
的右侧是bool2 && var1->DoSomething()
,因此如果bool2
为 true,则将评估var1->DoSomething()
。另请注意,即使var1
非空,e表达式的结果也并不总是您可能期望的结果。Since
&&
has higher precedence than||
, your expression is parsed as(var1 && bool1) || (bool2 && var1->DoSomething())
. Now sincevar1
is a null pointer, short circuit evaluation means thatbool1
is not evaluated, and the left hand side of||
evaluates as false. Thus to find out the value of the expression, the right hand side has to be evaluated (i.e. short-circuit evaluation does not kick in here!). The right hand side of||
isbool2 && var1->DoSomething()
, thus ifbool2
is true,var1->DoSomething()
will be evaluated. Note also that even forvar1
non-null, the result of the eexpression will not always be what you probably expected.简单的。
&&具有更高的优先级,因此您的表达式为:
尝试
否则第一个表达式
car1 && bool1
失败,并计算第二个表达式。因为 bool2 返回 true 显然,如果 bool2 为 true,则指针将被取消引用。在此处查找优先级列表: http://en.cppreference.com/w/cpp/language /operator_precedence 或使用谷歌。
Simple.
&& has higher precedence so your expression reads:
try
otherwise the first expression
car1 && bool1
fails and the second expression is evaluated. since bool2 returns true apparently your pointer is dereferenced if bool2 is true.look here for a precedencelist: http://en.cppreference.com/w/cpp/language/operator_precedence or use google.