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_ptr
s 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?
draw
takes an rvalue reference, you don't know for sure if it accepts ownership, or just takes a look and ignores the pointer. – Supermandraw
to take rvalue reference only to "take a look"? – Outfightdraw
, not really. But in general a function might throw an exception before it has completed its work. Then, who knows? – Supermandraw
takes rvalue reference only to take a look, it's not following GotW#91. But that's just GotW#91 as best practices. Maybe the coding convention being used in some code was (in my opinion) not best practices... but is still perfectly legal code (awkwardness aside). – Frighteneddraw
might take ownership conditionally. (E.g., "If there is nothing to draw, then ignore the parameter since we have no use for it.") Thereset
forces the resource to be released ifdraw
chose not to consume it. – Selfsupportingstd::move
doesn't really do anything directly. So it is indeed to the internals of draw what do with it (though I must admit I find the fact that the code needs documenting quite surprising, it would be more consistent for draw to always take ownership. So bad example) – Standard