Ah, thanks. That would indeed save a line.I just mean if you know what move constructors do in the language, you can take advantage of move constructors others have written. For one, virtually everything in the standard library is movable.
One copy is unavoidable, after all that was part of the stated purpose of the function. The question was whether you can make the code cleaner without sacrificing performance. For instance, would this work?
Code:vector<stuff> copy_and_alter(vector<stuff> source) { ... } // at call site auto altered = copy_and_alter(old_data);
It does seem to me that it would almost mask why it's efficient, though. If you declare a variable explicitly and then use a function like this:
Code:
vector<stuff> result;
copy_and_alter(old_data, result);
...then in that case it's pretty obvious that no matter what type the result is, a reference is being passed and no huge copy is occurring. You could even put it on one line instead of two if you didn't mind being silly with two semicolons on the same line.
With the shorter syntax, you have to know that your target object has a move assignment operator implemented, because otherwise (unless I'm missing something) you're going to be doing a full, slow copy. With the use of "auto", this becomes even less explicit, since you don't see the type right in front of you.
If you know that you're always going to be using objects with move assignment operators, then great, but otherwise it seems like a bit of a trap for maintainability and performance if you ever changed the vector<stuff> to SomeHugeCustomObject instead, all to save one line.
I realize this is almost certainly an out-of-date opinion though. I also dislike references for the same reasons. If you pass a pointer as a method parameter, it's instantly obvious that the method might modify the data. If you pass an object as a reference, you have to take an extra step to check the header file, hover over the code, remember offhand, or whatever, in order to be SURE that it's a reference and not a copy. I like the extra, instant, obviousness in code.