Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to avoid a copy when returning an argument from a function?

Tags:

c++

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?

like image 704
Maks Verver Avatar asked Aug 31 '25 16:08

Maks Verver


1 Answers

If you do want to reverse the string in-place so that the change to the string you send in as an argument is visible at the call site and you also want to return it by value, you have no option but to copy it. They are two separate instances.


One alternative: Return the input value by reference. It'll then reference the same object that you sent in to the function:

MyType& Reverse(MyType& value) {   // doesn't work with r-values
    std::reverse(std::begin(value), std::end(value));
    return value;
}

MyType Reverse(MyType&& value) {   // r-value, return a copy
    std::reverse(std::begin(value), std::end(value));
    return std::move(value);       // moving doesn't really matter for ints
}

Another alternative: Create the object you return in-place. You'll then return a separate instance with RVO in effect. No moves or copies. It'll be a separate instance from the one you sent in to the function though.

MyType Reverse(const MyType& value) {
    // Doesn't work with `std::array`s:
    return {std::rbegin(value), std::rend(value)}; 
}

The second alternative would work if std::array could be constructed from iterators like most other containers, but they can't. One solution could be to create a helper to make sure RVO works:

using MyType = std::array<int, 26>;

namespace detail {
    template<size_t... I>
    constexpr MyType RevHelper(const MyType& value, std::index_sequence<I...>) {
        // construct the array in reverse in-place:
        return {value[sizeof...(I) - I - 1]...};    // RVO
    }
} // namespace detail

constexpr MyType Reverse(const MyType& value) {
    // get size() of array in a constexpr fashion:
    constexpr size_t asize = std::tuple_size_v<MyType>;

    // RVO:
    return detail::RevHelper(value, std::make_index_sequence<asize>{});
}
like image 152
Ted Lyngmo Avatar answered Sep 02 '25 05:09

Ted Lyngmo