_ptr , .
void MyFunc()
{
std::unique_ptr<Foo> foo = std::make_unique<Foo>();
}
Foo unique_ptr. , -, , new , delete - . unique_ptr , , unique_ptr ( ).
unique_ptr unique_ptr.
, unique_ptr, const. unique_ptr .
:
std::unique_ptr<Foo> foo1 = std::make_unique<Foo>();
std::unique_ptr<Foo> foo2 = std::move(foo1);
Now the pointer to is foo1moved to foo2. foo1no longer manages this memory, foo2is.
The lifetime of an object managed by const std :: unique_ptr is limited by the area in which the pointer was created.
This means that when your unique_ptr leaves the scope, it deletes the object that it points to. As if you did it:
void MyFunc()
{
Foo* foo = new Foo()
// ... do some stuff, then return
delete foo;
}
The advantage is that now you don’t have to manually delete it, which is good because it is a potential memory leak if you forget to delete it.
source
share