C++ bitwise copy of object failing? Why?

删除回忆录丶 提交于 2019-12-08 13:16:45

问题


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()");
} ///:~

回答1:


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.




回答2:


Because copy constriuctor is missing . you must incrementing in copy constructor as well

add this line too

HowMany(const HowMany& r) { objectCount++; }



回答3:


You are having the issue that in your function f() the copy-constructor is called, which is not the normal constructor. When the function goes out of scope the the destructor will be invoked. Provide a copy constructor like

HowMany::HowMany(const HowMany& other){
 objectCount++;
}

and this will work.




回答4:


Try creating a copy constructor for HowMany . By default a copy constructor would be created by compiler for you and you would not feel it getting called.



来源:https://stackoverflow.com/questions/17184962/c-bitwise-copy-of-object-failing-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!