-2
class MyClass
{
    public:
        MyClass()
        {
            std::cout << "MyClass Constructor" << std::endl;
        }

        ~MyClass()
        {
            std::cout << "MyClass Destructor" << std::endl;
        }
};

int main()
{
    MyClass* p = new MyClass();
}

What is the difference between calling p->~MyClass(); OR delete p;

Both call the destructor.

user1833852
  • 51
  • 2
  • 10
  • `delete` also returns the allocated memory to the OS. I don't think it is even legal to call the destructor explicitly like this, anyway – Code-Apprentice Jul 04 '17 at 03:51
  • 3
    @Code-Apprentice Explicitly calling the destructor is legal, but in this case, you can't explicitly call the destructor, as you need to `delete` the memory, and `delete` calls the destructor, which would call the destructor twice, which is illegal. – Justin Jul 04 '17 at 03:56
  • @Code-Apprentice If it weren't legal anywhere, the language wouldn't allow you to write it – Passer By Jul 04 '17 at 04:08
  • @Code-Apprentice , Justin calling destructor usually viable if you are to destroy object created by placement new (i.e., no memory was allocated, object created inside of pre-existing buffer) – Swift - Friday Pie Jul 04 '17 at 05:10

1 Answers1

2

Using the new operator will:

  1. Allocate a chunk of memory.
  2. Call the constructor for the class, with this pointing at that memory.

delete is just the undoing of what new does, so it will, by default:

  1. Call the destructor with this pointing to its memory block.
  2. Free the memory block.

You can overload these operators to behave differently, of course.

Mitch
  • 1,839
  • 16
  • 23