メインコンテンツ

AUTOSAR C++14 Rule A18-1-3

The std::auto_ptr shall not be used

説明

ルール定義

std::auto_ptr は使用しないものとします。

根拠

std::auto_ptr は、C++11 言語標準の移動セマンティクスの導入を以前に戻すクラス テンプレートのタイプです。ソース std::auto_ptr オブジェクトをターゲット オブジェクトにコピーすると、ソース オブジェクトが変更されます。コンパイラは、ソース オブジェクト内のリソースの所有権をターゲット オブジェクトに移し、ソース オブジェクトを null ポインターに設定します。この異常なコピー構文により、コピー操作後にソース オブジェクトを使用すると、予期せぬ動作につながる可能性があります。std::auto_ptr の使用がセグメンテーション違反につながる次のコード スニペットを考えてみましょう。

void func(auto_ptr<int> p) {
	cout<<*p;
	//...
}

int main()
{
	std::auto_ptr<int> s = new int(1);
	//..
	func(s); // This call makes s a null-pointer
	//...
	func(s); // exception, because s is null
	return 1;
}

1 つ目の func() の呼び出しによって、ソース std::auto_ptr オブジェクト s が引数 p にコピーされ、p へのポインターの所有権が移され、s が null ポインターに設定されます。再度 func() が呼び出されると、コンパイラが null ポインター s にアクセスしようとして、セグメンテーション違反が発生します。

std::auto_ptr 型のオブジェクトは、標準テンプレート ライブラリ (STL) のように、コピー操作でソース オブジェクトが無効にされないと想定している汎用コードとも互換性がありません。std::auto_ptr は使用しないでください。C++11 では非推奨になっており、C++17 以降で削除されます。C++11 言語標準では、std::auto_ptr の安全な代替手段として std::unique_ptr が導入されています。std::auto_ptr の代わりに std::unique_ptr を使用してください。

Polyspace 実装

Polyspace® は、C スタイル配列内を除いて、コード内の std::auto_ptr のすべてのインスタンスにフラグを設定します。

トラブルシューティング

ルール違反が想定されるものの、Polyspace から報告されない場合は、コーディング規約違反が想定どおりに表示されない理由の診断を参照してください。

すべて展開する

このコードは、Polyspace がコード内の std::auto_ptr にどのようにフラグを設定するかを示します。

#include <cstdint>
#include <memory>
#include <vector>
#define AUTOPTROF(_TYPE) std::auto_ptr<_TYPE>
AUTOPTROF(int) v_int;                           // Noncompliant
typedef struct {
	std::auto_ptr<bool> vb;                     // Noncompliant
} T;
T vec; 
typedef std::auto_ptr<int> my_int_auto_ptr;     // Noncompliant
void Fn() noexcept
{
      
	std::auto_ptr<std::int32_t> ptr1(new std::int32_t(10)); // Noncompliant
	std::unique_ptr<std::int32_t> ptr2 =
	std::make_unique<std::int32_t>(10);         // Compliant
	std::vector<std::auto_ptr<std::int32_t>> v;  // Noncompliant
}

int main(){
	//..
}

Polyspace は、std::auto_ptr オブジェクトにフラグを設定します。std::auto_ptr の代わりに std::unique_ptr を使用してください。

チェック情報

グループ: 言語サポート ライブラリ
カテゴリ: Required、Automated

バージョン履歴

R2020a で導入