Why doesn't the C++ default destructor destroy my objects?

前端 未结 13 2138
刺人心
刺人心 2020-12-14 06:59

The C++ specification says the default destructor deletes all non-static members. Nevertheless, I can\'t manage to achieve that.

I have this:

class N         


        
13条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 07:41

    I think you could benefit from a very simple example:

    int main(int argc, char* argv[])
    {
      N* n = new N();
    } // n is destructed here
    

    This will not print anything either.

    Why ? Because the pointer (n) is destructed, not the object pointed to *n.

    Of course, you would not want it to destroy the object pointed to:

    int main(int argc, char* argv[])
    {
      N myObject;
      {
        N* n = &myObject;
      } // n is destructed here, myObject is not
    
      myObject.foo();
    } // myObject is destructed here
    

    You should remember that unlike languages like C# or Java, there are 2 ways to create objects in C++: directly N myObject (on the stack) or via new like in new N() in which case the object is placed on the heap and YOU are reponsible for releasing it at a later time.

    So your destructor destroys the pointer, but not the object pointed to. Allocate the object without new (and without using a pointer) or use a Smart Pointer if you want it to be automatic.

提交回复
热议问题