MISRA C++:2023 Rule 23.11.1
The raw pointer constructors of std::shared_ptr and std::unique_ptr should not be used
R2024b 以降
説明
ルール定義
The raw pointer constructors of std::shared_ptr and std::unique_ptr should not be used. 1
根拠
new 演算子の使用と、その結果得られる生のポインターを std::unique_ptr または std::shared_ptr オブジェクトに変換することとによってメモリを割り当てる代わりに、たとえば以下のようにします。
class numberClass {
public:
numberClass(int n): number(n){}
private:
int number;
}
int aNumber=1;
std::unique_ptr<numberClass> numberUniquePtr (new numberClass(aNumber));
std::shared_ptr<numberClass> numberSharedPtr (new numberClass(aNumber));std::make_unique または std::make_shared 関数を使用して、直接 std::unique_ptr または std::shared_ptr オブジェクトを作成します。次に例を示します。auto numberUniquePtr = std::make_unique<numberClass>(aNumber); auto numberSharedPtr = std::make_shared<numberClass>(aNumber);
以下の理由で std::make_unique または std::make_shared を使用することを推奨します。
std::make_uniqueを使用したstd::unique_ptrオブジェクトの作成、またはstd::make_sharedを使用したstd::shared_ptrオブジェクトの作成は例外セーフで、実行時のパフォーマンスを向上させます。たとえば、new演算子を使用する動的メモリ割り当てとそれに続く変換がそれぞれ異なるステップで行われると、ステップの間で、メモリ リークの発生につながる例外が発生する可能性があります。より簡潔な構文を使用できます。動的に割り当てられるオブジェクトのデータ型を繰り返す必要はありません。
Polyspace 実装
チェッカーは以下にフラグを設定します。
new演算子から返された生のポインターからのstd::unique_ptrオブジェクト (またはboost::unique_ptrオブジェクト) の作成。new演算子から返された生のポインターからのstd::shared_ptrオブジェクト (またはboost::shared_ptrオブジェクト) の作成。
トラブルシューティング
ルール違反が想定されるものの、Polyspace® から報告されない場合は、コーディング規約違反が想定どおりに表示されない理由の診断を参照してください。
例
チェック情報
| グループ: General utilities library |
| カテゴリ: 推奨 |
バージョン履歴
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.