9

I was reading a question on SO and in one of the answers, it has been mentioned as:

If no unambiguous matching deallocation function can be found, propagating the exception does not cause the object’s memory to be freed.

So, if I just overload my new operator and not the delete operator, would any default delete operator be created and called; or, do I have to also write the delete operator explicitly.

Azeem
  • 11,148
  • 4
  • 27
  • 40
pasha
  • 2,035
  • 20
  • 34
  • When your overloaded `new` is successful without an exception or otherwise? If you have a particular scenario, please add that code sample in your question with some context. – Azeem Sep 04 '18 at 05:20
  • This passage talks about placement new. The regular operator new always has a matching delete whether you overload something or not. – n. m. could be an AI Sep 04 '18 at 05:41
  • @n.m., I agree with what you said about regular new, what would be invoked for placement new? would there be any default or nothing gets invoked? – pasha Sep 04 '18 at 05:46
  • @Azeem, when I invoke new and the constructor throws an exception. – pasha Sep 04 '18 at 05:48
  • As the passage says, if matching opetator delete is not found, nothing gets invoked. – n. m. could be an AI Sep 04 '18 at 05:53

1 Answers1

8

What this means is that if you overload operator new with extra arguments, and not the corresponding delete with extra arguments, if an exception occurs in a constructor, no delete operator will be called. On the other hand, if you're overloading the basic new (with no extra arguments), and an exception occurs, delete with no extra argument will be called, and that will be the default operator delete if you have not overloaded it.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • Just to be explicit, so if I invoke new with some arguments, the delete taking same arguments will be invoked, correct? – pasha Sep 04 '18 at 05:43
  • if (one of) the constructors invoked after the `operator new` function returns throws an exception, yes. – Chris Dodd Sep 04 '18 at 05:48