mercredi 16 août 2023

Do we really need to ensure giving up ownership when moving a `unique_ptr`?

I'm reading Nicolai M. Josuttis's C++ Move Semantics - The Complete Guide book (which is pretty good imho) and I'm not sure I agree with the comments in one of the examples.

Quote (from 6.1.2 - Guaranteed States of Moved-From Objects):

Similar code can be useful to release memory for an object that a unique pointer uses:

draw(std::move(up));  // the unique pointer might or might not give up ownership
up.reset();           // ensure we give up ownership and release any resource

Let's assume that the up variable is indeed unique_ptr and the draw function receives the unique_ptr by value (otherwise, what's the point of moving the pointer to a "passed-by-ref" function).

I understand that it is legal to call reset on a "moved-from" object. But what I do not understand is why it is "required" in order to "ensure we give up ownership and release any resource" and how is it possible that "the unique pointer might or might not give up ownership"?

After all, unique_ptrs cannot be copied and the whole idea is that they guarantee only one ownership.

So, afaik, if my two assumptions are correct, there is no need to call the reset function to ensure the ownership was given away.

Am I missing something?

Aucun commentaire:

Enregistrer un commentaire