gpt4 book ai didi

c++ - 为什么将指针转换为 bool 时会出现性能警告?

转载 作者:IT老高 更新时间:2023-10-28 13:58:50 25 4
gpt4 key购买 nike

这个问题延伸到 Why use !! when converting int to bool? .

当我做这样的事情时,我觉得我很酷:

bool hasParent() {
return this->parentNode;
}

当没有父节点时,this->parentNodeNULL

但我得到了:

warning C4800: 'Node *' : forcing value to bool 'true' or 'false' (performance warning)

即使使用 (bool) 强制转换,警告仍然不会消失。

怎么了,哟?为什么这是性能警告?我认为写这样的东西效率会降低:

bool hasParent() {
if (this->parentNode)
return true;
else
return false;
}

但是第二个版本没有产生任何警告,编译器似乎更开心了。哪个更快?

最佳答案

Microsoft Connect 上有关于此的讨论 (What is the performance implication of converting to bool in C++?)。给微软的例子是:

$ cat -n t.cpp && cl -c -W3 -O2 -nologo -Fa t.cpp
1 bool f1 (int i)
2 {
3 return i & 2;
4 }
5
6 bool f2 (int i)
7 {
8 const bool b = i & 2;
9 return b;
10 }
11
12 bool f3 (int i)
13 {
14 const bool b = 0 != (i & 2);
15 return b;
16 }
t.cpp
t.cpp(3) : warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)
t.cpp(8) : warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)

微软的回应(来自负责警告的开发人员)是:

This warning is surprisingly helpful, and found a bug in my code just yesterday. I think Martin is taking "performance warning" out of context.

It's not about the generated code, it's about whether or not the programmer has signalled an intent to change a value from int to bool. There is a penalty for that, and the user has the choice to use "int" instead of "bool" consistently (or more likely vice versa) to avoid the "boolifying" codegen. The warning is suppressed in the third case below because he's clearly signalled his intent to accept the int->bool transition.

It is an old warning, and may have outlived its purpose, but it's behaving as designed here

所以基本上 MS 开发人员似乎在说,如果你想将 int 'cast' 为 bool 你应该更正确地使用 "返回 this->parentNode != 0"而不是隐式或显式转换。

就我个人而言,我很想了解更多有关警告发现的错误类型的信息。我认为这个警告不会有很大的值(value)。

关于c++ - 为什么将指针转换为 bool 时会出现性能警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1847860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com