|The purpose of
delete is not to delete things. What?? But I'm serious. The purpose of
delete is to undo
As an approximation that will no doubt anger several C++ experts, you can view
new as a combination of
malloc and invoking the constructor, and you can view
delete as a combination of invoking the destructor and
free. That's not exactly literally how they work, but it's close enough that you can use that to reason about when you need them. (don't use this as an excuse to
delete something that was
Most of the time, if you want to get rid of something,
delete is the wrong way to do it - because most things were not created by
new. Trying to
delete something else results at best in a failing safety check but in general corrupts the state of your application.
Most objects are destroyed implicitly, in various ways. Local variables by exiting a scope, values in containers by the container being destroyed, smart pointers do most of the rest. Explicitly using
delete is occasionally necessary but it's probably better to actively avoid creating those cases. It's quite bug-prone, especially around exceptions and other non-trivial control flow.
In the sense that its destructor is invoked (so you can implement it and
Calin Negru wrote:later if you use “delete” on the pointer will that delete the content of the variable too?
delete the members that need to be deleted), yes. If you mean that in some other sense then, probably, no (but depending on what you mean).
Implementing classes with lots of raw-pointer members that you individually
delete in the destructor is very mid-2000s. Typical advice is to delegate that to smart pointers and containers as much as possible, with the goal of following the Rule of Zero instead of one of the other rules-of-some-number, but sometimes you just have to do what you have to do.