メインコンテンツ

AUTOSAR C++14 Rule A9-3-1

Member functions shall not return non-constant "raw" pointers or references to private or protected data owned by the class

説明

ルール定義

Member functions shall not return non-constant "raw" pointers or references to private or protected data owned by the class.

根拠

プライベートまたは保護されているクラス所有データへの非定数ポインターまたは参照を返すと、クライアントがインターフェイスを使用せずに外部からオブジェクトにアクセスして、オブジェクトの状態を変更することが可能になります。明示的なインターフェイスを使用しないこのようなアクセスでは、クラスのプライベート/保護されているデータ アクセス階層がバイパスされる可能性があります。その結果、予期しない動作やバグにつながる可能性があります。

このルールは、クラスにより所有されるデータに適用されます。異なるクラス間で共有されているオブジェクトへの非定数ハンドルが返される可能性があります。スマート ポインターとコンテナーを模倣するクラスは、このルールに違反しません。

Polyspace 実装

チェッカーは、メンバー関数が非静的データ メンバーへの非 const のポインターまたは参照を返す場合のみ、ルール違反にフラグを設定します。このルールは静的データ メンバーには適用されません。

トラブルシューティング

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

すべて展開する

#include <cstdint>
#include <memory>
#include <utility>

class A
{
  public:
    explicit A(std::int32_t number) : x(number) {}
    std::int32_t&
    GetX() noexcept // Noncompliant
    {
      return x;
    }
 
  private:
    std::int32_t x;
};

void Fn1() noexcept
{
  A a{10};
  std::int32_t& number = a.GetX();
  number = 15; // External modification of private class data
}

この例では class A メンバー関数 GetX()x (class A が所有するプライベート データ) を指す非定数の生ポインターを返します。Polyspace はこの実装に非準拠としてフラグを設定します。Fn1() は、プライベート クラス データを指す非定数の生ポインターを返すことで、number を保管および変更する、a.GetX() の問題を示します。このクラスは、クラス自体のプライベート データ メンバーに対する変更を制御できず、予期しない動作につながる可能性があります。


#include <cstdint>
#include <memory>
#include <utility>
class B
{
  public:
    explicit B(std::shared_ptr<std::int32_t> ptr) : sharedptr(std::move(ptr)) {}
    std::shared_ptr<std::int32_t> GetSharedPtr() const noexcept // Compliant 
    {
      return sharedptr;
    }
 
  private:
    std::shared_ptr<std::int32_t> sharedptr;
};

void Fn2() noexcept
{
  std::shared_ptr<std::int32_t> ptr = std::make_shared<std::int32_t>(10);
  B b1{ptr};
  B b2{ptr};
  *ptr = 50; // External modification of ptr which shared between b1 and b2
  // instances
  auto shared = b1.GetSharedPtr();
 
  *shared = 100;   // External modification of ptr which shared between b1 and
  // b2 instances
}

この例では、class B 関数 GetSharedPtr() が、インスタンス b1 および b2 の間で共有されているスマート ポインター変数を返します。Polyspace は、この実装に非準拠としてフラグを設定しません。


#include <cstdint>
#include <memory>
#include <utility>
class C
{
  public:
    explicit C(std::int32_t number)
      : ownedptr{std::make_unique<std::int32_t>(number)}
    {
    }
    const std::int32_t& GetData() const noexcept // Compliant
    {
      return *ownedptr;
    }
 
  private:
    std::unique_ptr<std::int32_t> ownedptr;
};
void Fn3() noexcept
{
  C c{10};
  const std::int32_t& data = c.GetData();
  // data = 20; // Cannot modify data, it is a const reference
}

この例では、GetData() は定数参照を返します。このメンバー関数を使用してプライベート クラス データを変更することはできません。Polyspace はこの実装に非準拠としてフラグを設定しません。

チェック情報

グループ: クラス
カテゴリ: Required、Partially automated

バージョン履歴

R2019a で導入