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

Does early return of the same variable prevent NRVO?

Here is the code:

std::vector<int> foo(bool cond) {
    std::vector<int> result;
    if (cond) {
        return result;      // (1)
    }
    result.push_back(42);
    return result;          // (2)
}

The same variable result is being returned from two places. Is that still considered as a condition for NRVO?

P.S. I realize that this code can be refactored to return this value from a single point, so my question is theoretical.

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

Update: Ok, NRVO is optional even in C++17. Is there any reason why multiple returns would prevent the compiler to use NRVO but the optimization would be used for a single return?

>Solution :

Does early return of the same variable prevent NRVO?

No, NRVO is still possible and most implementations will indeed use it in this situation.

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