When I am instating a class I need to perform a 'delete' after using the object even if the class has a destructor?

Asked

Viewed 61 times

1

If I instate a class and Gero an object from it obligatorily I have to displace the memory of that object at the end of its use, right? But if the class that originated my object has a destructor it will be necessary to delete the object even if the class with its destructor already does the memory offset job?

1 answer

1


Depends.

Allocate into stack so no need, this is an automatic memory and the compiler generates its own code that will displace whatever it takes.

If the allocation is in the heap need to know if the class does it for you, if it does, it is not necessary to do something else.

If you wrote the class then you need to analyze whether it is not the case to include memory management within it. The destructor may indicate that you release the memory, but this is not guaranteed, you need to see the documentation. If it does then you should not release the memory manually.

Still if it’s in the heap can use a smart pointer, then it takes care of dislocate for you. It is the most suitable whenever the class leave for the programmer to take care of the memory management.

If none of this is done, yes, you need dislocate memory under pain of causing a memory leak. It is not easy to do right in many cases, and even in the trivial it is easy to commit some slip.

  • When my pussui class a constructor I am obliged or recommended to use a destructor?

  • There is none of this, the destructor must only be created when there is need. In fact, most classes have no destructor. In general this occurs only when she herself makes an allocation in the heap and/or opens some external resource.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.