Will the original object be deleted if I return unique_ptr?

I want to do something like this:

unique_ptr<MyObj> MyFunc() {
  MyObj* ptr = new MyObj();
  ...
  return unique_ptr<MyObj>(ptr);
}

unique_ptr<MyObj> value = MyFunc();

But I'm not sure if the object will be deleted when the temporary value is destroyed after the function returns. If so, how should I correctly implement the function that returns unique_ptr?

+4
source share
4 answers

No, the object will not be deleted when the scope expires. This is due to the fact that the constructor of the move unique_ptr"moves" the semantics of ownership to the new object unique_ptr, and the destruction of the old unique_ptrwill not lead to the removal of the selected object.

. . unique_ptr<>, .

+10

, std::make_unique:

return std::make_unique<T>(/* your arguments*/);

, :

  • new std::bad_alloc,
  • MyObj
  • ptr , unique_ptr
+3

std:: make_unique. , . std:: make_shared.

, std:: move, unique_ptrs .

: return std::move(ptr);

+1

, ; MyFunc, . std::unique_ptr std::create_unique ( ). , , ; / ( ) , , main):

Created
999
Destroyed

:

#include <iostream>
#include <memory>

class MyObj
{
public:
  MyObj( int v )
  : value( v )
  {
    std::cout << "Created" << std::endl;
  }

  ~MyObj()
  {
    std::cout << "Destroyed" << std::endl;
  }

  int value;
};

std::unique_ptr<MyObj> MyFunc()
{
  auto ptr = std::make_unique<MyObj>( 999 );

  // ...do other stuff here?...

  // return std::move( ptr );  // Loki Astari says move() is unnecessary
  return ptr;
}

int main()
{
  auto p = MyFunc();
  std::cout << p->value << std::endl;
  return 0;
}
0

Source: https://habr.com/ru/post/1622793/