shared_ptr constructed from a raw new

ID

c.maintainability.make_shared

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Modernization

Language

C / C++

Description

Building a std::shared_ptr from a raw new performs two allocations (object + control block) and states the type twice. Use std::make_shared<T>(args…​), which allocates both together and is exception-safe.

Rationale

Building a std::shared_ptr from a raw new performs two allocations (object + control block) and states the type twice. Use std::make_shared<T>(args…​), which allocates both together and is exception-safe.

The following code illustrates the pattern detected by this rule:

void f() {
  // FLAGGED: shared_ptr constructed from a raw new
  std::shared_ptr<int> a(new int(5));

  // FLAGGED: shared_ptr constructed from a raw new
  auto b = std::shared_ptr<Foo>(new Foo(1, 2));

Remediation

Follow secure coding practices and review the references below for detailed remediation guidance.

Configuration

This detector does not need any configuration.