有时我想做
bool success= true;
success &&= dosmthing1();
success &&= dosmthing2();
success &&= dosmthing3();
if (success)
让我们忽略我可能正在使用异常......我的问题是它是否由 C++ 标准保证,对于我的用例来说,它的&=行为就像不存在&&=一样?...
编辑:做 smthing-s return bool
有时我想做
bool success= true;
success &&= dosmthing1();
success &&= dosmthing2();
success &&= dosmthing3();
if (success)
让我们忽略我可能正在使用异常......我的问题是它是否由 C++ 标准保证,对于我的用例来说,它的&=行为就像不存在&&=一样?...
编辑:做 smthing-s return bool
这取决于您期望&&=的工作方式。如果你想x &&= y();等价于x = x && y();,那么不,因为在这个表达式y()中,如果x开始为假,则不会被调用,但x &= y();它会是。
如果您不希望它发生短路并且您的所有表达式都确实具有类型bool(不是可转换为 的东西bool,如指针、整数或用户定义的对象),那么它可以工作。不过这有很多限制。
不,& 是按位与,&& 是布尔与。如果 dosmthing* 返回 1 或 0 以外的值,则结果会有所不同。
They are completely different. In this case, the short
circuiting of && seems important: if dosmthing1() returns
false, dosmthing2 and dosmthing3 would not be called if you
use &&. They will be called if you use &.
In this particular case, why not just write:
success = dosmthing1()
&& dosmthing2()
&& dosmthing3();
This seems just as clear (at least formatted like this), and
avoids any need for &&=.
不; 它不是短路。
bool x = false;
x &= (cout << "You shouldn't see me!");