C & C++

C & C++

Made by DeepSource

Found usage of std::auto_ptr instead of std::unique_ptr CXX-W2026

Bug risk
Minor
Autofix

std::unique_ptr is a smart pointer that was introduced in C++11 to replace std::auto_ptr. It is used to manage dynamically allocated objects that are not shared by multiple objects.

One of the main advantages of std::unique_ptr over std::auto_ptr is that it forces you to be explicit about transferring ownership, so it is visible and clear in the code.

When an std::auto_ptr is copied, the ownership of the managed object is transferred to the copy, leaving the original object in an undefined state. This means that using std::auto_ptr in containers, for example, could result in unexpected behavior. In other words with std::auto_ptr a silent transfers of ownership is likely. This also impacts the readability the code, as it’s not always clear whether ownership is transferred, or it is intentional.

Bad practice

void foo() {
  std::auto_ptr<int> num1(new int);
  // after this program point `num1` is NULL but it's not clear from the
  // context, if this is intentional
  std::auto_ptr<int> num2 = num1;
}

Recommended

void foo() {
  std::unique_ptr<int> num1(new int);
  // due to a call to std::move it's clear that programmer wants to move `num1`
  // to `num2`
  std::unique_ptr<int> num2 = std::move(num1);
}

References