Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning to a variable which was moved in right side of expression

Tags:

c++

c++14

Is this undefined behavior or not?

std::unique_ptr<T> p = some_function();

p = some_other_function(std::move(p));

I've read http://en.cppreference.com/w/cpp/language/eval_order but not found definitive answer there.

like image 395
vladon Avatar asked Dec 07 '25 08:12

vladon


1 Answers

If you search for assignment then you will find rule 8 with only mentions the built-in assignment operator, and std::unique_ptr do overload the assignment operator.

But since the operator is overloaded, the statement

p = some_other_function(std::move(p));

is actually a function call:

p.operator=(some_other_function(std::move(p)));

which makes it part of rule 3 instead. And that makes it well-defined (because std::move(p) have to be done before some_other_function is called, and some_other_function have to finish before p.operator= is called).

like image 138
Some programmer dude Avatar answered Dec 12 '25 09:12

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!