Created
December 11, 2013 04:12
-
-
Save lexdene/7904992 to your computer and use it in GitHub Desktop.
在C++中,Foo a = Foo()是否会调用复制构造函数。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
using namespace std; | |
class Foo{ | |
public: | |
Foo(){ | |
cout << "Foo constructor" << endl; | |
} | |
Foo(const Foo&){ | |
cout << "Foo copy contructor" << endl; | |
} | |
}; | |
int main(){ | |
cout << "case a:" << endl; | |
Foo a(); | |
cout << "case b:" << endl; | |
Foo b; | |
cout << "case c:" << endl; | |
Foo c = Foo(); | |
return 0; | |
} | |
/* | |
# 输出: | |
case a: | |
case b: | |
Foo constructor | |
case c: | |
Foo constructor | |
# 解释: | |
case a什么也不会输出, | |
因为它只是声明了一个函数。 | |
函数的返回值类型是Foo,函数名是a,参数列表为空。 | |
case b和case c输出一样, | |
case c并没有经过复制构造函数, | |
查看汇编代码可以看见, | |
它把复制构造的过程优化掉了。 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment