简体   繁体   中英

Am I testing the Return Value Optimization correctly?

Consider:

struct Measures {
    char name[128]; // added in response to comments
    int   age;
    float weight;
};

Measures foo() {
    Measures res;
    cout << &res << endl;
    return res;
}

int main() {
    Measures m = foo();
    cout << &m << endl;
    system("pause");
    return 0;
}

The output I get by running this code in Visual Studio is:

004FFA30
004FFB28

Do I conclude correctly from the fact that the two addresses differ that the return value optimization is not performed? If so, why would it not be performed in this case (I found several posts dealing with Visual Studio 2017 (version 15.9.14) not performing the Return Value Optimization, but none of them seems to be about this particular case)?

https://godbolt.org/z/FCRtY9

As hinted at in the comments, this has to do with the size of your struct. If the struct fits in registers, then the address might change.

Once you create a bigger struct, the address stays the same.

Note that copy-elision is guaranteed to occur: https://stackoverflow.com/a/48881336/461597

#include <iostream>
using std::cout;
using std::endl;

struct Measures {
    int   age;
    float weight;
};

struct BigMeasures {
    Measures m;
    int foo, bar, moo, mar;
};

Measures foo() {
    Measures res;
    cout << &res << endl;
    return res;
}

BigMeasures bar() {
    BigMeasures res;
    std::cout << &res << "\n";
    return res;
}

int main() {
    std::cout << "Small Measures:\n";
    Measures m = foo();
    cout << &m << endl;
    std::cout << "Big Measures:\n";
    BigMeasures bm = bar();
    std::cout << &bm << "\n";
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM