Say we have a struct:
struct S{ int _i = 1; };
I would like to write a function which updates an instance of S
, like this:
void update(S& s) { s._i += 1; }
I usually prefer to return values rather than passing an argument by reference and changing it. Something like this:
S update(S s)
{
S ret = std::move(s);
ret._i += 1;
return ret;
}
I would then be able to call this last function like this (in case I want a copy of the previous and updated instance):
S s{};
S u = update(s);
Or like this (in case I'm only interested in keeping the updated value):
S s{};
s = update(std::move(s)); // is this legal?
So, I move s
into the argument of the update
function, and retrieve it back at the assignment (last line). Is this legal? Apart from that, is this just silly and should I go with the first solution?
(s)`, which essentially means "I don't care what state `s` is in afterwards" and gives permission to the compiler to scavenge it for parts. It appears that in your case, `S` doesn't actually contain any parts that can be scavenged (detached from `s` and transferred to another `S` instance), so moving is once again no different than copying. The only question is whether a smart optimizer could see though all these calls, avoid copying and perform the update in place.– Igor Tandetnik May 16 '21 at 00:29