简体   繁体   English

我是否正确测试了返回值优化?

[英]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:我通过在 Visual Studio 中运行此代码得到的输出是:

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)?如果是这样,为什么在这种情况下不执行它(我发现一些处理 Visual Studio 2017(版本 15.9.14)的帖子没有执行返回值优化,但似乎没有一个是关于这种特殊情况的)?

https://godbolt.org/z/FCRtY9 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请注意,保证会发生复制省略: 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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