主要内容

MISRA C++:2023 Rule 8.2.5

reinterpret_cast shall not be used

自 R2024b 起

描述

reinterpret_cast shall not be used. 1

理由

使用运算符 reinterpret_cast,可在不相关的类型之间进行转换,这可能会导致未定义行为。为避免未定义行为,请不要使用 reinterpret_cast

作为例外,在以下情况下允许使用 reinterpret_cast,因为这些转换的行为是明确定义的:

  • 将指针转换为指向 T*,其中 Tvoidcharunsigned charstd::byte 之一,并带有 cv 限定符。

  • 将指针 p 转换为足以表示指针值的整数类型,例如 std::uintptr_t

Polyspace 实现

Polyspace® 针对使用 reinterpret_cast 运算符报告违反了此规则。作为例外,使用以下各项不会被报告为违规:

  • reinterpret_cast<T*>,其中 Tvoidcharunsigned charstd::byte 之一。

  • reinterpret_cast<T>(p),其中 p 是一个指针,T 是一个足以表示指针值的整数。

故障排除

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

示例

全部展开

此示例显示 reinterpret_cast 可以在不相关的类型(例如 A*uint32_t*)之间进行转换。在此类不相关的类型之间进行转换会导致未定义行为。Polyspace 会针对此类用法报告违反了此规则。

#include <cstdint>
#include <array>
class A {};
void foo(A* p1) {
	uint32_t *p2 = reinterpret_cast< uint32_t * >(p1);    //Noncompliant
}

void bar(uint8_t* p1) {
	uint32_t *p2 = reinterpret_cast< uint32_t * >(p1);    //Noncompliant
}

void func(float* x) {
	
	reinterpret_cast<void*>(x); //Compliant by exception
	reinterpret_cast<char*>(x);//Compliant by exception
	reinterpret_cast<std::byte*>(x);//Compliant by exception
	reinterpret_cast<unsigned char*>(x);//Compliant by exception
}

作为例外,在已定义行为的情况下,允许使用 reinterpret_castfunc() 函数显示了此类合规用例的示例。

检查信息

组:表达式
类别:必需
PQL 名称:std.misra_cpp_2023.R8_2_5

版本历史记录

在 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++:2008

  • MISRA C++:2023

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