Rule A20-8-1 (required, implementation, automated)

An already-owned pointer value shall not be stored in an unrelated smart pointer.

Rationale

Smart pointers (e.g. std::shared_ptr) that allow to manage the same underlying pointer value using multiple smart pointer objects, shall be created in a way that creates a relationship between two smart pointer objects (e.g. via copy assignment). Unrelated smart pointer objects with a pointer value that is owned by another smart pointer object shall not be created.

Example

// $Id: A20-8-1.cpp 305588 2018-01-29 11:07:35Z michal.szczepankiewicz $

#include <memory>

void Foo()
{
uint32_t *i = new uint32_t{5};

std::shared_ptr<uint32_t> p1(i);
std::shared_ptr<uint32_t> p2(i); // non-compliant
}

void Bar()
{
std::shared_ptr<uint32_t> p1 = std::make_shared<uint32_t>(5);
std::shared_ptr<uint32_t> p2(p1); //compliant
}

See also

SEI CERT C++ Coding Standard [10]: MEM56-CPP: Do not store an alreadyowned pointer value in an unrelated smart pointer