Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Will dereferencing an r-value reference do anything?

So let’s say I have this code:

std::unique_ptr<int> ptr = std::make_unique<int>(10);

int val = *std::move(ptr);

// Anything using ptr after

I know that std::move gives us an r-value reference to the unique_ptr, and I don’t think dereference will steal the resources from ptr like a move assignment operator would, so would this code be any different at all without the std::move?

Like if I wanted the resources allocated for ptr to be freed after its value was set into val, would this achieve that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To find out if *std::move(ptr) does anything to the unique pointer you need to read documentation for std::unique_ptr::operator* (for example here: https://en.cppreference.com/w/cpp/memory/unique_ptr/operator*) to find it has only one overload:

typename std::add_lvalue_reference<T>::type operator*() const
noexcept(noexcept(*std::declval<pointer>()));

It is a const method. It cannot not modify the unique pointer.

Ergo, in general std::move is just a cast, here it has no effect. * dereferences the unique pointer and a copy of the contained int is made. The unique pointer is not modified by *std::move(ptr).

Like if I wanted the resources allocated for ptr to be freed after its value was set into val, would this achieve that?

No. You can call std::unique_ptr::reset() if you want the unqiue pointer to free the object.


A bit more handwaving….

As already mentioned std::move is just a cast. You can think of std::move(x) as pretending that x would be a temporary. Now, consider that it would be rather useless to let the dereferene operator make a temporary unique pointer free its resource. Its a temporary so anyhow it will get its destructor called.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading