继续问复制控制
一个非常简单的程序如下:
#include <iostream>
using namespace std;
class Foo {
public:
Foo(int i) { cout << "using int. done." << endl; }
~Foo() { cout << "deleting. done." << endl; }
//private:
Foo(const Foo &f) { cout << "using copying. done." << endl; }
};
int main() {
Foo f = 100;
return 0;
}
运行结果为:
using int. done.
deleting. done.
分析Foo f = 100这句,应该是先调用Foo(int)来构造临时对象,再调用拷贝构造函数Foo(const Foo &f)来构造f,然后再删除临时对象。
但奇怪的是:拷贝构造函数Foo(const Foo &f)似乎并没有被调用,析构函数也只被调用了一次;而如果将Foo(const Foo &f)设为private,则不能编译。
谁能解释一下?谢谢