0

I have a question about deleting an object and pointers to them. First test:

  a test;
  a* test_ptr;
  test_ptr = &test;
  test.aPrint();
  test_ptr->aPrint();
  delete(test_ptr);
  test.aPrint();

I've added printout in the constructor, destructor and function aPrint prints the text "aPrint" (ob).

constructor
aPrint
aPrint
destructor
aPrint
destructor

How can I get a call to the destructor twice? And how can I still use object test after deletion?

-----edit-----

So if I use new instead. Then I have to use delete or else I got leakage.

a* test_ptr;
test_ptr = new a;
test_ptr->aPrint();
delete(test_ptr);

Is this because this example uses the heap were the first example uses the stack?

2 Answers 2

1

Since your object is on stack, its destructor will be called when this object will go out of the scope.

You are deleting one times and compiler is calling destructor implicitly another time.

That is why destructor is called twice.

However, behaviour of such program is not defined and be ready for any side-effect of double deletion.

Sign up to request clarification or add additional context in comments.

Comments

1

The object wasn't allocated using new, so it's undefined behavior to call delete. Just let it go out of scope, and the destructor will be called automatically (the second call in your example).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.