【问题标题】:Different behaviour of returning class object from a function [duplicate]从函数返回类对象的不同行为[重复]
【发布时间】:2015-04-22 12:33:03
【问题描述】:

以下代码

class Foo
{
public:
    Foo() {a = 1;};
    Foo(const Foo&) :a(2) {};
    int a;
};

Foo foo()
{
    Foo a;
    return a; 
}

int main(int argc, char* argv[])
{
    Foo f = foo();
    std::cout << f.a << std::endl;

    return 0;
}

在 Mac(使用 g++)和 VS2013 上的工作方式不同。在 Mac 上打印 1,而在 Windows 上打印 2。那为什么foo()按值返回类对象时程序不调用拷贝构造函数呢?

【问题讨论】:

  • 用 VS2013 开启优化,你会看到和 g++ 一样的结果(两个结果都没有错,我相信答案会很清楚)。

标签: c++ class constructor copy


【解决方案1】:

此行为是由于 MAC 中省略了额外的副本。在 Visual Studio 中开启优化可能会带来类似的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    相关资源
    最近更新 更多