Does std::move invalidates the raw pointer points to something owned by unique_ptr?

Viewed 927

If I have a unique pointer and I took a pointer to the something owned by unique_ptr:

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 make me understand what happens here or what standard says about this.

2 Answers

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 adress of your ressource and the raw pointer of t get's set to nullptr. 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 adress is still valid after the move to d. At this point t has nothing to do with your integer anymore, its just a std::unique_ptr<int> that is currently not assigned. Your raw pointer m will remain valid until the currently owning unique_ptr actually deletes it, for example because it goes out of scope.

Transferring the ownership of the integer between std::unique<int> objects, from t to d, does not affect m because m doesn't own the integer. m is a raw pointer (i.e., int *), it never participates in the ownership of the integer.

If m doesn't outlive the object that owns the integer – which is d by the end of your snippet – there can't be any issue.

Related