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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With