15

I recently discovered std::optional as a way to improve the clarity of my code, especially for return value of functions. However I had questions about its impact on performance. More specifically I wanted to know if it was possible to write a code similar to the one below that would allow the compiler to apply Named Return Value Optimization.

struct Data
{
    int x;
    int y;
};

std::optional<Data> makeData(bool condition)
{
    Data data;

    if(condition)
    {
        data.x = 2.0;
        data.y = 2.0;

        return data;
    }
    else
    {
        return {};
    }
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
Romain D.
  • 310
  • 1
  • 2
  • 10

1 Answers1

15

Well, in this case, the as-if rule is enough already: Data is trivially copyable and trivially destructible, so you cannot observe whether the compiler copies it, or whether it directly constructs it into the std::optional<Data> return object. NRVO is not needed in order to prevent the copy.

Let's suppose you gave Data a copy constructor with a side effect. Then the question of whether NRVO applies would be relevant. The answer is no: NRVO doesn't apply, because the local variable's type differs from the function return type. In order to allow NRVO to happen, you might write something like this:

std::optional<Data> r;
if (condition) {
    r.emplace();
    r.x = 2.0;
    r.y = 2.0;
}
return r;
Brian Bi
  • 111,498
  • 10
  • 176
  • 312