Suppose I have value type with some in-place operation. For example, something like this:
using MyType = std::array<100, int>;
void Reverse(MyType &value) {
std::reverse(value.begin(), value.end());
}
(The type and operation can be more complicated, but the point is the operation works in-place and the type is trivially copyable and trivially destructible. Note that MyType is large enough to care about avoiding copies, but small enough that it probably doesn't make sense to allocate on the heap, and since it contains only primitives, it doesn't benefit from move semantics.)
I usually find it helpful to also define a helper function that doesn't change the value in-place, but returns a copy with the operation applied to it. Among other things, that enables code like this:
MyType value = Reversed(SomeFunction());
Considering that Reverse()
operates in-place, it should be logically possible to calculate value
without copying the result from SomeFunction()
. How can I implement Reversed()
to avoid unnecessary copies? I'm willing to define Reversed() as an inline function in a header if that's what's necessary to enable this optimization.
I can think of two ways to implement this:
inline MyType Reversed1(const MyType &value) {
MyType result = value;
Reverse(result);
return result;
}
This benefits from return-value optimization but only after the argument value
has been copied to result
.
inline MyType Reversed2(MyType value) {
Reverse(value);
return value;
}
This might require the caller to copy the argument, except if it's already an rvalue, but I don't think return-value optimization is enabled this way (or is it?) so there's a copy upon return.
Is there a way to implemented Reversed()
that avoids copies, ideally in a way that it's guaranteed by recent C++ standards?