简体   繁体   English

复合分配到bool安全吗?

[英]Is compound assignment to bool safe?

I came across code like this and it made me cringe: 我遇到了这样的代码,这让我感到畏缩:

bool isEventSent = false;

if(type >= EVENT_BEGIN && type < EVENT_END)
{
    isEventSent |= m_SendToSubscribers(event);
}

return isEventSent;

The intent is clear, but I've never used compound assignment with bools like that and it makes me feel uneasy. 意图很明确,但我从未将复合赋值与类似的布尔值一起使用,这让我感到不安。 Is this code safe? 此代码安全吗? And if not, what would be a case it could fail? 如果没有,它将在什么情况下失败?

EDIT: 编辑:

I know that a |= b is equivalent to a = a | b 我知道a |= b等于a = a | b a = a | b , but I am wondering whether a | b a = a | b ,但我想知道是否a | b a | b instead of a || b a | b代替a || b a || b could cause problems for booleans under some circumstances. a || b在某些情况下可能会导致布尔值出现问题。

It is perfectly correct. 这是完全正确的。 The compound operator a |= b means a = a | b 复合运算符a |= b表示a = a | b a = a | b , so isEventSent |= m_SendToSubscribers(event); a = a | b ,因此是isEventSent |= m_SendToSubscribers(event); means isEventSent = isEventSent | m_SendToSubscribers(event); 表示isEventSent = isEventSent | m_SendToSubscribers(event); isEventSent = isEventSent | m_SendToSubscribers(event); . Both individual operators ( = and | ) are well defined for bool s. bool s分别定义了两个运算符( =| )。

Perfectly safe. 万无一失。 The a |= b is mostly equivalent to doing a = a | a | = b最等同于做a = a | b.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM