Why is the destructor getting called twice but the

2019-01-20 16:10发布

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?

4条回答
Root(大扎)
2楼-- · 2019-01-20 16:21

Implement a copy constructor and check again:

CTemp(const CTemp& rhs){
        printf("\nIn copy cons");
    }
查看更多
太酷不给撩
3楼-- · 2019-01-20 16:32

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

查看更多
Ridiculous、
4楼-- · 2019-01-20 16:36

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.

查看更多
我只想做你的唯一
5楼-- · 2019-01-20 16:44
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.

查看更多
登录 后发表回答