主要内容

MISRA C++:2023 Rule 8.2.2

R2026b

C-style casts and functional notation casts shall not be used

自 R2024b 起

描述

C-style casts and functional notation casts shall not be used. 1

理由

C 样式强制转换在源代码中难以区分。从一种类型强制转换为另一种类型时,无法传达开发人员的意图。包含 C 样式强制转换的代码难以理解和调试。应避免使用 C 样式强制转换。

C++ 引入了显式强制转换操作,这些操作易于识别,并能清晰传达每次强制转换背后的开发人员意图。请改用这些强制转换操作。

Polyspace 实现

Polyspace® 会标记代码中 C 样式强制转换。合规的 C++ 样式强制转换操作包括:

  • std::static_cast

  • std::reinterpret_cast

  • std::const_cast

  • std::dynamic_cast

  • 使用 {} 表示法进行强制转换

此外,也允许使用 boost 库中的 reference_cast 操作和 Microsoft 库中的 safe_cast 操作。

故障排除

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

示例

全部展开

#include <cstdint>
class Base
{
public:
	explicit Base(std::int32_t) {}
	virtual void Fn() noexcept {}
};
class Derived : public Base
{
public:
	void Fn() noexcept override {}
};
class myClass
{
};
std::int32_t G() noexcept
{
	return 7;
}

void Foo() noexcept(false)
{
	Base obj = Base{10};        // Compliant
	const Base obj3(5);
	Base* obj4 = const_cast<Base*>(&obj3);        //Compliant
	Base* obj2;
	myClass* d1 = reinterpret_cast<myClass*>(obj4); // Compliant 
	Derived* d2 = dynamic_cast<Derived*>(obj2);       // Compliant
	std::int16_t var1 = 20;
	std::int32_t var2 = static_cast<std::int32_t>(var1);      // Compliant
	std::int32_t var4 = 10;
	float f1 = static_cast<float>(var4);                    // Compliant

	std::int32_t var5 = static_cast<std::int32_t>(f1);      //Compliant

	std::uint32_t var7 = std::uint32_t{0};//Compliant
	static_cast<void>(G());                               //Compliant
}
void Bar(){
	Base obj = Base{1};
	Base* obj2 = (Base*)(&obj); //Noncompliant
	std::int16_t var1 = 20;
	std::int32_t var3 = (std::int32_t)var1;                   // Noncompliant
	float f = (float)var3;                                 // Noncompliant
	std::int32_t var6 = (std::int32_t)f;                   // Noncompliant
}

在此示例中,函数 Foo() 显示了多个 C++ 样式强制转换操作。这些操作易于识别,用途清晰。例如,在 Base* obj4 = const_cast<Base*>(&obj3) 中,可以清楚地看出强制转换操作删除了 obj3 中的 const 限定符。这些强制转换操作是合规的,Polyspace 不会标记它们。

函数 Bar() 显示了多个 C 样式强制转换。这些操作难以发现和理解。Polyspace 会标记这些 C 样式强制转换。

检查信息

组:表达式
类别:必需
PQL 名称:std.misra_cpp_2023.R8_2_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.