C++: why it doesn't call a destructor?

后端 未结 3 1198
傲寒
傲寒 2020-12-21 07:32

I use extra brackets in my code. I thought when the destructor should be called after the local variable scope is ended but it doesn\'t work like this:

class         


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-21 08:15

    This answer is good enough but just to add some more.

    I see you have been coded with Java. In C++ to create variable/object in stack keyword new is not needed. Actually when you use keyword new your object is creating in heap and it doesn't destroys after leaving scope. To destroy it you need to call delete in your case delete test;

    In such a structure as yours, after leaving scope you just lose pointer what points into object, so after leaving scope you cannot free memory and call destructor, but eventually OS call destructor just after exit() instruction is executed.

    To sum up C++ != Java

提交回复
热议问题