考虑:

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;
}

通过在Visual Studio中运行此代码得到的输出是:
004FFA30
004FFB28

我可以从两个地址不同之处在于,不执行返回值优化这一事实来得出正确的结论吗?如果是这样,为什么在这种情况下不执行此操作(我发现有几篇有关Visual Studio 2017(版本15.9.14)的文章没有执行返回值优化,但似乎都与这种情况无关)?

最佳答案

https://godbolt.org/z/FCRtY9

正如评论中所暗示的,这与您的结构的大小有关。如果该结构适合寄存器,则地址可能会更改。

创建更大的结构后,地址将保持不变。

请注意,肯定会发生复制删除: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;
}

08-16 00:48