Home > Software design >  Will C function with mixed constant value and variable enable copy elision too?
Will C function with mixed constant value and variable enable copy elision too?

Time:03-29

In the following code

std::string OtherFunc();

std::string MyFunc() {
    if (condition1) return "result 1";
    if (condition2) return "result 2";
    return OtherFunc();
}

Will MyFunc() enable copy elision (for the return string from OtherFunc())? I know I can write

std::string MyFunc() {
    std::string ret;

    if (condition1) {
        ret = "result 1";
        return ret;
    }

    if (condition2) {
        ret = "result 2";
        return ret;
    }

    ret = OtherFunc();
    return ret;
}

to 100% sure copy elision enable. But I think the 2nd code is very cumbersome.

CodePudding user response:

There are no std::string copies/moves made in the first example you are showing. (since C 17)

In the second variant the move from ret to the return value of the function (or whatever object is initialized from it) may be elided (named return value optimization (NRVO)), but that is not guaranteed, even in C 17.

Furthermore in the second example, even if NRVO is applied, there will need to be a move assignment operator call for the line ret = OtherFunc(); that isn't required in the first version.

So, the first version is definitively better in terms of the required copy/move operations. (A std::string move can still be cheap, so the difference may not be significant enough that other factors won't determine the overall performance.)

  •  Tags:  
  • c
  • Related