Why is the destructor getting called twice but the constructor only once?

℡╲_俬逩灬. 提交于 2019-11-28 14:20:27
void Dowork(CTemp obj)

Here local-copy will be done, that will be destruct after exit from scope of DoWork function, that's why you see destructor-call.

Implement a copy constructor and check again:

CTemp(const CTemp& rhs){
        printf("\nIn copy cons");
    }

When the function is called its parameter is created by using the implicit copy constructor. Add to your class the following copy constructor

CTemp( const CTemp & ){
    printf("\nIn ccons");
}

to see one more message about creating an object

You've missed to count a copy-constructor and expected a constructor instead.

CTemp * obj = new CTemp(); // It will call a constructor to make
                           // a pointer to a constructed object.

and

Dowork(*obj);              // It will copy `*obj` to the `Dowork` and copy-
                           // constructor will be called to make the argument

So, you have two objects and two destructor will be called.

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