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

梦想的初衷 提交于 2019-11-27 08:38:11

问题


My code is

class CTemp{
public:
    CTemp(){
        printf("\nIn cons");
    }
    ~CTemp(){
        printf("\nIn dest");
    }
};

void Dowork(CTemp obj)
{
    printf("\nDo work");
}

int main()
{
    CTemp * obj = new CTemp();
    Dowork(*obj);
    delete obj;
    return 0;
}

The output that I get is

In cons
Do work
In dest
In dest

Now why does the constructor get called once but the destructor is called twice? Can someone please explain this?


回答1:


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.




回答2:


Implement a copy constructor and check again:

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



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/20216971/why-is-the-destructor-getting-called-twice-but-the-constructor-only-once

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