This is probably a simple question, but: If a program uses the delete operator, is a destructor not needed? This is in "C++".
Asked
Active
Viewed 383 times
1
-
`delete` calls the destructor. User-defined destructors are rarely needed anyway, though, and neither is `delete`ing something. – chris Jun 17 '13 at 22:24
-
What do you mean by uses a `delete` operator and destructor not needed? You get always a free destructor from the compiler. Also `delete` should go together with a `new` operator while the destructor goes together with the constructor. – Alexandru Barbarosie Jun 17 '13 at 22:25
-
4I feel a rule of three reference coming... – Michael Dorgan Jun 17 '13 at 22:26
-
@MichaelDorgan: Self-fulfilling prophesy in action! – Jim Lewis Jun 17 '13 at 22:45
1 Answers
3
The delete operator is not a substitute for a destructor...it will cause the destructor to be invoked.
The compiler will supply a default destructor, if you do not define one yourself. Whether the default destructor is sufficient, or whether you need to supply your own, is a completely separate issue from whether you use the delete operator explicitly, or merely allow the object to go out of scope.
Edit: Since Michael Dorgan mentioned it, I might as well add this:
The rule of three (also known as the Law of The Big Three or The Big Three) is a rule of thumb in C++ that claims that if a class defines one of the following it should probably explicitly define all three:
destructor copy constructor copy assignment operator

Jim Lewis
- 43,505
- 7
- 82
- 96
-
It's several years too late to be teaching the Rule of Three. http://stackoverflow.com/q/4782757/103167 – Ben Voigt Jun 17 '13 at 23:22
-
Perhaps, but not completely and I will also add that many locations are not allowed to code in C++11 yet so it still has much value. – Michael Dorgan Jun 18 '13 at 21:26