Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is moving twice in a single full expression allowed

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?

like image 494
Toby Brull Avatar asked Jan 23 '15 14:01

Toby Brull


1 Answers

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.

like image 138
Mike Seymour Avatar answered Oct 12 '22 01:10

Mike Seymour