[英]When does the compiler creates the copy-constructor in C++?
For example in the code below : 例如,在下面的代码中:
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()");
}
Why does the compiler doesn't create the copy-constructor automatically for the class HowMany, and bit-wise copy takes place when the call to f(h) takes place ? 为什么编译器不会为HowMany类自动创建复制构造函数,并且在调用f(h)时会发生逐位复制?
In what cases the compiler creates the default copy-constructor and in what cases it doesn't create? 在什么情况下,编译器会创建默认的复制构造函数,在什么情况下它不会创建?
It gives output as: 它输出为:
after construction of h: objectCount = 1
在构造h之后:objectCount = 1
x argument inside f(): objectCount = 1
f()中的x参数:objectCount = 1
~HowMany(): objectCount = 0
~HowMany():objectCount = 0
after call to f(): objectCount = 0
在调用f()之后:objectCount = 0
~HowMany(): objectCount = -1
~HowMany():objectCount = -1
~HowMany(): objectCount = -2
~HowMany():objectCount = -2
Many many thanks in advance 许多人提前感谢
In C++98 and C++03 the compiler always creates a copy constructor, that performs a memberwise copy of your fields, unless you specify explicitly that you wrote your own 1 . 在C ++ 98和C ++ 03中,编译器总是创建一个复制构造函数,它执行字段的成员复制,除非您明确指定自己编写了1 。
This is what happens in your code: the compiler-generated copy constructor doesn't do anything particular - in particular, it doesn't increment objectCount
- so you end up with a negative object count (all the copied objects didn't increment the counter, but they did decrement it). 这就是你的代码中发生的事情:编译器生成的拷贝构造函数没有做任何特别的事情 - 特别是,它不会增加
objectCount
- 所以你最终得到一个负对象计数(所有复制的对象都没有增加反击,但他们确实减少了它)。
To obtain the result you expected, you would have to write something like: 要获得预期的结果,您必须编写如下内容:
HowMany(const HowMany &) {
objectCount++;
}
for every object compiler should create copy constructor, here also copy constructor created for all object h, x and h2. 对于每个对象编译器应该创建复制构造函数,这里还复制为所有对象h,x和h2创建的构造函数。 But for h object copy constructor is no need.
但是对于h对象复制构造函数是没有必要的。 And next you are calling a function f with input argument as h.
接下来,您将调用带有输入参数的函数f作为h。 Here copy constructor invokes and it copies the content in h to x object.
这里复制构造函数调用并将h中的内容复制到x对象。 And for the next object h2 also same thing (here also copy constructor invokes and copies x to h2).
而对于下一个对象h2也是一样的(这里也是复制构造函数调用并将x复制到h2)。 Becuase of this reason only objectcount not incremented.
由于这个原因,只有objectcount没有递增。 thank you.
谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.