是 !!在 C++ 中转换为 bool 的安全方法?

2023-06-03C/C++开发问题
5

本文介绍了是 !!在 C++ 中转换为 bool 的安全方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

[这个问题与这个.]

如果我尝试将某些类型的值用作布尔表达式,则会收到警告.我有时会使用三元运算符 (?:) 来转换为 bool,而不是取消警告.使用两个非运算符 (!!) 似乎做同样的事情.

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.

我的意思是:

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?

那么,双重非技术真的能做同样的事情吗?它比三元技术更安全还是更不安全?这种技术对于非整数类型是否同样安全(例如,void *double 用于 T)?

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)?

我不是在问 !!t 是否是好的风格.我在问它在语义上是否与 t 不同?真:假.

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

推荐答案

!运算符和三元运算符的第一个参数都隐式转换为 bool,所以 !!和?:IMO 是演员的愚蠢的多余装饰.我投给

The argument of the ! operator and the first argument of the ternary operator are both implicitly converted to bool, so !! and ?: are IMO silly redundant decorations of the cast. I vote for

b = (t != 0);

无隐式转换.

这篇关于是 !!在 C++ 中转换为 bool 的安全方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6