C ++对象失败的逐位复制?为什么? [英] C++ bitwise copy of object failing? Why?
问题描述
这问题是关于类对象按位复制。
为什么构造函数不叫,反而析构函数在下面code叫什么名字?
输出结果
的howmany H2 = F(H); //没有构造得到; S这里所说的..
施工小时后:objectCount = 1
里面f()的参数x:objectCount = 1
〜的howmany():objectCount = 0
调用F()后:objectCount = 0
〜的howmany():objectCount = -1
〜的howmany():objectCount = -2
一流的howmany {
静态INT objectCount;
上市:
的howmany(){objectCount ++; }
静态无效打印(常量字符串和放大器;味精=){
如果(msg.size()!= 0)的cout&所述;&下;味精<< :;
COUT<< objectCount =
<< objectCount<< ENDL;
}
〜的howmany(){
objectCount--;
打印(〜的howmany());
}
};INT的howmany :: objectCount = 0;
//传递和返回按值:的howmany F(的howmany X){
x.print(内˚FX参数());
返回X;
}诠释主(){
的howmany H;
::的howmany打印(建设小时后);
H2的howmany = F(H);
::的howmany打印(调用F()后);
} ///:〜
首先,C ++没有按位复制。默认的复制机制是由实现编译器提供的拷贝构造函数的。编译器提供的拷贝构造函数拷贝递归调用每个数据成员的具体语义复制每个数据成员。最终的结果可能inded看起来像在某些情况下,按位复制,但尽管如此,语言不使用这种低层次的概念。
其次,被称为在这种情况下,构造函数,再次的拷贝构造函数的。它的签名是
的howmany ::的howmany(常量的howmany&安培;)
这构造是由编译器提供,它的确是叫,但你根本不指望它。这就是为什么你的 objectCount
计数器显示disbalanced结果。
This question is regarding bitwise copying of class objects. Why is constructor not called, instead destructor is called in below code ? The output is as
HowMany h2 = f(h); // No constructor get;s called here..
after construction of h: objectCount = 1
x argument inside f(): objectCount = 1
~HowMany(): objectCount = 0
after call to f(): objectCount = 0
~HowMany(): objectCount = -1
~HowMany(): objectCount = -2
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()");
} ///:~
Firstly, C++ does not have "bitwise copying". The default copying mechanism is implemented by compiler-provided copy constructor. Compiler-provided copy constructor recursively copies each data member by invoking each data member's specific copying semantics. The end result might inded look like a "bitwise copy" in some cases, but nevertheless the language does not use such a low-level concept.
Secondly, the constructor that is called in this case is, again, copy constructor. It's signature is
HowMany::HowMany(const HowMany&)
This constructor is provided by the compiler and it is indeed called, yet you are simply not counting it. That is why your objectCount
counter shows disbalanced result.
这篇关于C ++对象失败的逐位复制?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!