16

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?

levzettelin
  • 2,600
  • 19
  • 32

1 Answers1

20

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • 7
    Shameless plug: I wrote an article on [the sequencing rules](http://josephmansfield.uk/articles/c++-sequenced-before-graphs.html) that helps by visualising the rules with graphs. – Joseph Mansfield Jan 23 '15 at 14:27
  • 2
    @JosephMansfield I want to buy you a beer. – bolov Jan 23 '15 at 16:15