主要内容

MISRA C++:2023 Rule 7.0.2

R2026b

There shall be no conversion to type bool

自 R2024b 起

描述

There shall be no conversion to type bool. 1

理由

从基础类型转换为 bool 依赖于编译器将任何非零值视为 true。这与遵循 POSIX 标准并使用特定整数返回代码的 API 冲突。例如,返回值 -1 可能表示错误,但编译器会将此值隐式转换为 true。

此外,到 bool 的上下文转换的结果可能不符合开发人员的预期。因此,如果需要 bool 转换(例如 if 语句),请使用显式计算结果为 bool 类型的表达式。

Polyspace 实现

当您执行从基础类型到 bool 类型的上下文转换时,规则检查项会报告违规。

在以下情况下,转换为 bool 是合规的:

  • 将大小为 1 的位字段的值转换为 bool,因为值 0 转换为 false,而值 1 转换为 true。

  • 对具有 explicit operator bool 表达式的类类型使用 static_cast<bool>。

  • 执行从指针或具有 explicit operator bool 表达式的类到 bool 的上下文转换。

  • 使用其条件形式为 type-specifier-seq declarator 的 while 循环。这是合规的,因为若要用类似方法实现与 while 循环相同的结果,需要对象具有不必要的作用域宽度。

故障排除

如果您预期会出现违规,而 Polyspace® 未报告该违规,请参阅诊断为何编码规范违规未按预期显示。

示例

全部展开

int exampleA(){
	class BoolConvertible {
	public:
		explicit operator bool() const { return true; } 
	};

	BoolConvertible obj;
	if (obj) {                        //Compliant
		//...
	}

	struct MyClass {
		int data;
	};
	
	
	int MyClass::*mptr = nullptr;
	if (mptr) {                        //Noncompliant
		//...
	}

	enum Color { RED, GREEN, BLUE };
	Color color = GREEN;
	if (color) {                       //Noncompliant
		//...
	}

	double value = 0.0;
	while (value) {                    //Noncompliant
		//...
	}

	int num = 42;
	if (num) {                         //Noncompliant
		//...
	}
}

在此示例中:

  • 类 BoolConvertible 包含一个 explicit operator bool 表达式,使得从 obj 转换为 bool 类型合规。

  • 变量 mptr、color、value 和 num 到 bool 类型的上下文转换均不合规。

检查信息

组:标准转换
类别:必需
PQL 名称:std.misra_cpp_2023.R7_0_2

版本历史记录

在 R2024b 中推出


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C:2025

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.