Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Will C++ function with mixed constant value and variable enable copy elision too?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading