Is !! a safe way to convert to bool in C++?

2019-01-08 08:15发布

[This question is related to but not the same as this one.]

If I try to use values of certain types as boolean expressions, I get a warning. Rather than suppress the warning, I sometimes use the ternary operator (?:) to convert to a bool. Using two not operators (!!) seems to do the same thing.

Here's what I mean:

typedef long T;       // similar warning with void * or double
T t = 0;
bool b = t;           // performance warning: forcing 'long' value to 'bool'
b = t ? true : false; // ok
b = !!t;              // any different?

So, does the double-not technique really do the same thing? Is it any more or less safe than the ternary technique? Is this technique equally safe with non-integral types (e.g., with void * or double for T)?

I'm not asking if !!t is good style. I am asking if it is semantically different than t ? true : false.

17条回答
时光不老,我们不散
2楼-- · 2019-01-08 08:21

I would use bool b = t and leave the compile warning in, commenting on this particular line's safety. Disabling the warning may bite you in the butt in another part of the code.

查看更多
小情绪 Triste *
3楼-- · 2019-01-08 08:23

!! may be compact, but I think it is unnecessarily complicated. Better to disable the warning or use the ternary operator, in my opinion.

查看更多
仙女界的扛把子
4楼-- · 2019-01-08 08:24

If you're worried about the warning, you can also force the cast: bool b = (bool)t;

查看更多
Explosion°爆炸
5楼-- · 2019-01-08 08:29

The double not feels funny to me and in debug code will be very different than in optimized code.

If you're in love with !! you could always Macro it.

#define LONGTOBOOL(x) (!!(x))

(as an aside, the ternary operator is what I favor in these cases)

查看更多
做个烂人
6楼-- · 2019-01-08 08:30

I really hate !!t!!!!!!. It smacks of the worst thing about C and C++, the temptation to be too clever by half with your syntax.

bool b(t != 0); // Is the best way IMHO, it explicitly shows what is happening.

查看更多
该账号已被封号
7楼-- · 2019-01-08 08:31

I would use b = (0 != t) -- at least any sane person can read it easily. If I would see double dang in the code, I would be pretty much surprised.

查看更多
登录 后发表回答