例如在下面的代码中:
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
非常感谢提前