Assume one has a function with the following prototype
template<typename T>
std::unique_ptr<T> process_object(std::unique_ptr<T> ptr);
The function may return (a moved version of) the object that was passed to it, or a completely different object.
Is it legal C++ to use this function as follows?
std::unique_ptr<Widget> pw(new Widget());
pw = process_object(std::move(pw));
If I remember correctly, there is a C/C++ rule that forbids modifying an object more than once in a single full expression. Does this rule apply here? If yes, is there some way to express this idiom differently in a single line?
What if one replaces std::unique_ptr
by the despised std::auto_ptr
?
Is it legal C++ to use this function as follows?
Yes, that's fine.
If I remember correctly, there is a C/C++ rule that forbids modifying an object more than once in a single full expression.
Not quite. You can't modify an object more than once (or modify it and use its value) with unsequenced accesses.
Does this rule apply here?
No. Evaluating the function argument is sequenced before the function call, which is sequenced before the assignment. So the two accesses are sequenced, and all is good.
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