メインコンテンツ

このページの内容は最新ではありません。最新版の英語を参照するには、ここをクリックします。

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_cast の使用は許可されます。関数 func() は、このような準拠したユース ケースの例を示しています。

チェック情報

グループ: Expressions
カテゴリ: Required

バージョン履歴

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.