【发布时间】:2012-06-07 12:38:36
【问题描述】:
例如在下面的代码中:
class HowMany {
static int objectCount;
public:
HowMany() {
objectCount++;
}
static void print(const string& msg = "") {
if(msg.size() != 0)
cout << msg << ": ";
cout << "objectCount = " << objectCount << endl;
}
~HowMany() {
objectCount--;
print("~HowMany()");
}
};
int HowMany::objectCount = 0;
// Pass and return BY VALUE:
HowMany f(HowMany x) {
x.print("x argument inside f()");
return x;
}
int main() {
HowMany h;
HowMany::print("after construction of h");
HowMany h2 = f(h);
HowMany::print("after call to f()");
}
为什么编译器不会为类 HowMany 自动创建复制构造函数,而在调用 f(h) 时会发生按位复制?
在什么情况下编译器会创建默认的复制构造函数,在什么情况下不创建?
输出如下:
h 构造后:objectCount = 1
f() 中的 x 参数:objectCount = 1
~HowMany(): objectCount = 0
调用 f() 后:objectCount = 0
~HowMany(): objectCount = -1
~HowMany(): objectCount = -2
非常感谢提前
【问题讨论】:
-
你怎么知道 itd 没有创建? (顺便说一句,您的标题说“可以”,而您的问题说“不可以”。先解决这个问题。)
-
检查它的输出。我问的是它什么时候自动创建,什么时候不自动创建。
-
输出在哪里?您希望我们编译并执行您的代码以查看输出吗?然后回答?
-
您所说的按位复制是默认的复制构造函数。
-
您希望为 objectCount 打印什么,您看到了什么?
objectCount不会被自动生成的复制构造函数触及!
标签: c++ copy-constructor