Search code examples
c++unique-ptr

Does std::move invalidate a raw pointer obtained from unique_ptr::get()?


Suppose I have a unique pointer and I take a copy of its raw pointer like this:

auto t = std::make_unique<int>(67);
auto m = t.get();
auto d = std::move(t);
std::cout << *m;

 

I know m will be valid until t is modified or destroyed.

But when I move ownership from t, m is still valid.

Could someone help me understand what happens here, and what the standard says about this?


Solution

  • m is a raw pointer to the integer owned by t. auto d = std::move(t); transfers ownership to a new smart pointer d. The internal raw pointer of d gets set to the address of your resource and the raw pointer of t gets set to a null pointer.

    The integer that is now owned by d is still at the exact same location as before. That is why your raw pointer m that you got from t to that address is still valid after the move to d.

    At this point t has nothing to do with your integer any more; it's just a std::unique_ptr<int> that is currently not assigned. Your raw pointer m will remain valid until the currently owning unique pointer actually deletes it, for example because it goes out of scope.