Lifetime of an object managed by const std :: unique_ptr

Below I see the notes in the std::unique_ptrlink :

Only non-constant unique_ptrcan transfer ownership of the managed object to another unique_ptr. The lifetime of an object controlled by const std::unique_ptris limited by the area in which the pointer was created.

Is there anyone who can explain this with an example? I could not understand why.

+4
source share
4 answers

You simply cannot go from const std::unique_ptr, and you cannot use other modifying member functions - swap, releaseand reseteither (they are logically inconsistent, cannot be called on const).

, , , .


const std::unique_ptr ( ).
std::unique_ptr const& -const) std::unique_ptr (const correctness).

+10

reset, release, swap, - const std::unique_ptr. , a const std::unique_ptr , .

+3

unique_ptr , :

std::unique_ptr<int> p(new int(1));
std::unique_ptr<int> q(std::move(p)); 
//now q owns the pointer, which is freed when q is destructed

p const, , , p :

const std::unique_ptr<int> p(new int(1));
std::unique_ptr<int> q(std::move(p));  //compilation error
+3

_ptr , .

void MyFunc()
{ 
    // Creates a unique pointer that points at a Foo object.
    std::unique_ptr<Foo> foo = std::make_unique<Foo>();

    // ... do some stuff, then return
}

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.

+2
source

All Articles