Is std :: unique_ptr :: get returned after moving unique_ptr?

Consider the following code snippet:

class Owner { public: Owner(std::unique_ptr<int> ptr) : owned_pointer<int>(std:move(ptr)) {} private: std::unique_ptr<int> owned_pointer; }; std::unique_ptr<int> ptr(new int); int* ptr1 = ptr.get(); Owner new_owner(std::move(ptr)); 

Is it possible to assume that ptr1 is valid as long as new_owner remains in scope? This seems to work, but I cannot find a specification that states that it is explicitly - this is an undefined behavior / implementation, and I just work for me, or the code above is valid (ptr1 is guaranteed to indicate the pointer moves while it remains alive)?

+7
c ++ 11 unique-ptr move
source share
2 answers

Yes, the C ++ 11 specification ensures that transferring ownership of an object from one unique_ptr to another unique_ptr does not change the location of the object itself and that get() on the second unique_ptr returns the same as the first unique_ptr before the transfer.

Looking at N3337, section 20.7.1:

  1. In addition, u may, upon request, transfer ownership to another unique index u2 . Upon completion of such a transfer, the following postconditions:

    • u2.p is equal to the advance transmission up ,
    • up is nullptr , and
    • if the pre-transmission state ud saved, this state has been transferred to u2.d

where u is a unique_ptr object that stores the up pointer.

The first bullet directly answers the question, since get() indicated as returning up .

+3
source share

Yes it really is.

You can have several (simple) pointers pointing to the same object. The question is how long these pointers are valid or when the object pointed to is deleted.

A unique_ptr stores another simple pointer and passes into the property, that is, it is responsible for the destruction of the object. Moving it to another unique_ptr just transfers the property, the object itself is the same, and all pointers to it indicate that they remain valid.

Only when the property is not transferred (or released) and the owner of unique_ptr destroyed, does it also destroy the object. This will be the moment when all simple pointers pointing to an object become dangling pointers and play them, will be illegal.

+8
source share

All Articles