Is !! a safe way to convert to bool in C++?(是 !!在 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 的安全方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是 !!在 C++ 中转换为 bool 的安全方法?
基础教程推荐
- 提升 ASIO 流缓冲 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- c++ STL设置差异 2022-01-01
