Update a struct by returning a moved parameter instead of passing by reference

130 Views Asked by At

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?

0

There are 0 best solutions below