Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

unique-ptr

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?

like image 587
Owl66 Avatar asked Jun 14 '26 05:06

Owl66


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 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.

like image 180
Eric Avatar answered Jun 15 '26 17:06

Eric


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.

like image 30
ネロク・ゴ Avatar answered Jun 15 '26 19:06

ネロク・ゴ