Destructor being called twice when being explicitly invoked

后端 未结 10 467
孤街浪徒
孤街浪徒 2020-11-30 11:10

I was experimenting with destructors in C++ with this piece of code:

#include 

struct temp
{
    ~temp() { std::cout << \"Hello!\" <         


        
10条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 11:39

    I see that "Hello!" is being printed twice. shouldn't the calling of the destructor free the object and the destructor shouldn't be called again when it goes out of scope. Or is there some other concept ?

    That's correct.

    I must mention that im not intending to do this in practice. Im just trying to understand whats going on here.

    You've called the destructor, preparing an object to be destroyed. But this is also done automatically when an object goes out of scope, before it's actually de-allocated.

    The thing to understand is this: If you do things that don't make sense, then bad things happen. So don't do things that don't make sense. If you manually call a destructor, the descructor runs. That has no effect on anything else unless the destructor actually does something that has an effect.

提交回复
热议问题