【发布时间】: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