【问题标题】:warning C4800: 'BOOL' : forcing value to bool 'true' or 'false' (performance warning)警告 C4800: 'BOOL' : 强制值为 bool 'true' 或 'false' (性能警告)
【发布时间】:2014-04-25 06:42:00
【问题描述】:

当我在 Visual Studio 2008 中编译以下代码 sn-p 代码时,我收到此警告。

BOOL
CPlan::getStandardPlan() const
{
    return m_standardPlan;
}


bool m_bStandardPlan;

if(plan!=NULL)
{
    // Assign the values to the Cola object
    poCola->m_lPlanId           = plan->getPlanId();
    poCola->m_lPlanElementId        = plan->getPlanElementId();
    poCola->m_lPlanElementBaseId        = plan->getPlanElementBaseId();
    poCola->m_bStandardPlan         = plan->getStandardPlan(); //C4800

    return 1;
}

我参考了以下链接,

http://msdn.microsoft.com/en-us/library/b6801kcy%28v=vs.90%29.aspx

Forcing value to boolean: (bool) makes warning, !! doesnt

Warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)

我不确定如何解决此警告。

【问题讨论】:

  • 为什么不首先使用bool 而不是BOOL 作为返回值呢?
  • @Henrik 如果 user3360310 没有采用微软的“prefix-everything-with-C”表示法,CPlan 看起来很像一些 MS 库中的类,因此无法更改签名。

标签: c++ visual-studio visual-c++


【解决方案1】:

BOOL 是 WinAPI 中某处 int 的 typedef。 WinAPI 是一个 C API,所以他们不能使用 C++ 的bool。如果您无法通过从函数返回 bool 来摆脱它,例如因为您不维护该功能,所以您可以使用对零的显式检查来消除警告:

poCola->m_bStandardPlan = (plan->getStandardPlan() != 0);

另一个考虑是添加一个封装检查的函数:

bool getStandardPlan(CPlan const& plan) {
  return plan->getStandardPlan() != 0;
}

然后

poCola->m_bStandardPlan = getStandardPlan(plan);

【讨论】:

【解决方案2】:

getStandardPlan() 返回一个BOOL,它实际上是int 的typedef(0 被插入为false,所有其他值作为true)。我通常用三元运算符来解决这个问题。

poCola->m_bStandardPlan = plan->getStandardPlan() ? true : false;

【讨论】:

  • 谢谢@k4rlsson。我现在明白为什么编译器会抛出这个警告。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-23
  • 1970-01-01
  • 1970-01-01
  • 2012-01-10
  • 1970-01-01
相关资源
最近更新 更多