V825. Expression is equivalent to moving one unique pointer to another. Consider using 'std::move' instead.

The analyzer has detected a code fragment where the functions 'std::unique_ptr::reset' and 'std::unique_ptr::release' are used together.

Consider the following simple example:

void foo()
{
  auto p = std::make_unique<int>(10);
  ....
  std::unique_ptr<int> q;
  q.reset(p.release());
  ....
}

Technically, this call is equivalent to moving a smart pointer:

void foo()
{
  auto p = std::make_unique<int>(10);
  ....
  auto q = std::move(p);
  ....
}

Here, replacing the call chain 'q.reset(p.release())' with the 'q = std::move(p) ' expression, as suggested by the analyzer, would make the code more transparent. However, sometimes moving a smart pointer is necessary – for example, when using a user-defined deleter:

class Foo { .... };

struct deleter
{
  bool use_free;

  template<typename T>
  void operator()(T *p) const noexcept
  {
    if (use_free)
    {
      p->~T();
      std::free(p);
    }
    else
    {
      delete p;
    }    
  }
};

Here are two examples. The first one demonstrates using the 'reset' – 'release' pattern to move a smart pointer with a user-defined deleter:

void bar1()
{
  std::unique_ptr<Foo, deleter> p { (int*) malloc(sizeof(Foo)),
                                     deleter { true } };
  new (p.get()) Foo { .... };

  std::unique_ptr<Foo, deleter> q;

  q.reset(p.release()); // 1
}

The second example demonstrates doing the same operation using the 'std::move' function:

void bar2()
{
  std::unique_ptr<Foo, deleter> p { (int*) malloc(sizeof(Foo)),
                                    deleter { true } };
  new (p.get()) Foo { .... };

  std::unique_ptr<Foo, deleter> q;

  q = std::move(p);     // 2
}

In the second example, while moving the 'p' pointer to 'q', the 'std::move' function allows moving the deleter as well. This would not be possible using the 'q.reset(p.release())' call chain in the first example. Instead, the source object of type 'Foo' allocated on the heap by calling 'malloc' and constructed by the 'placement new' operator would be incorrectly freed by calling the 'delete' operator. That would inevitably result in undefined behavior.


Bugs Found

Checked Projects
411
Collected Errors
14 123
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site. Learn More →
Accept