Main Content

AUTOSAR C++14 Rule A20-8-7

A std::weak_ptr shall be used to represent temporary shared ownership.

Since R2022a

Description

Rule Definition

A std::weak_ptr shall be used to represent temporary shared ownership.

Rationale

A std::shared_ptr is deallocated when the reference count drops to zero. If the code creates a reference cycle by using multiple std::shared_ptr, the reference count of any std::shared_ptr involved in the cycle can never drop to zero. This can cause a memory leak.

Use std::weak_ptr to break up reference cycles. A std::weak_ptr can point to a std::shared_ptr but does not increase the reference count.

Polyspace Implementation

Polyspace® raises this defect when assigning by using the assignment operator of std::shared_ptr. If the right side is a class or struct field of type std::shared_ptr that is instantiated with a template that has only a std::shared_ptr template argument, Polyspace flags this defect.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <memory>

template <template <typename> class T, typename U>
struct Base {
  T<U> sPoint;
};

template <typename T>
using Ex1 = Base<std::shared_ptr, T>;

struct spExampleA;
struct spExampleB : public Ex1<spExampleA> {};
struct spExampleA : public Ex1<spExampleB> {};


void example()
{
  std::shared_ptr<spExampleB> sp1 = std::make_shared<spExampleB>();
  std::shared_ptr<spExampleA> sp2 = std::make_shared<spExampleA>();
  sp1->sPoint = sp2;             // Noncompliant
  sp2->sPoint = sp1;             // Noncompliant

}

The preceding code creates a reference cycle with std::shared_ptr. In the example, neither sp1 nor ps2 can have their reference count drop to 0 and be deallocated. Use std::weak_ptr instead of std::shared_ptr to break reference cycles.

Check Information

Group: General utilities library
Category: Required, Non-automated

Version History

Introduced in R2022a