Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, any general guidelines for handling memory allocation/deletion?

Probably all that I'm asking for is a link to a website that I have yet to find. But coming from a Java background, what are the general guidelines for handling memory allocation and deletion in C++? I feel like I may be adding all sorts of memory leaks to my application. I realize that there are several variants of smart pointers, and you can mention them too me as well, but I'd like to focus on standard C++ pointers.

like image 778
JnBrymn Avatar asked Nov 27 '22 01:11

JnBrymn


2 Answers

My usual policy is this

  • Use smart pointers where usage is at all complex.
  • All raw pointers are owned by a specific object that is responsible for deleting it.
  • The constructor always either allocates the pointer or initializes it to null if it's to be set later.
  • The destructor always deletes any contained pointers
  • Those rules ensure that pointers get deleted when their owning objects are deleted eliminating most common memory leak situations.
  • Never pass an internal pointer into another object, always pass the container object and have the the called function call member functions of the container object to act on the "pointer".
  • Disable copying of the container object. In rare cases implement the copy so that it copies the pointed to object. But never allow the owning object to be copied without also copying the contained object.
  • The previous two rules ensure that you can't have copies of the pointer pointing to deleted memory.
  • Don't try to implement reference counting. If you need a reference counted pointer use a smart pointer class and contain that.

I've found those rules generally ensure you can use raw pointers safely and efficiently, and if you want to break those rules then use a smart pointer instead.

like image 151
jcoder Avatar answered Dec 19 '22 06:12

jcoder


Usually, we use new to allocate memory, and delete to free it. (Mainly because new calls the appropriate constructors, and delete the appropriate destructors).

But most of people here will advise you against using raw pointers other than for educational purposes (well except when the overhead of smart pointers is significant, like in embedded programming).

Knowing of things work is important, but in most cases, you can take advantage of well designed smart pointers classes to make things easier for you (and often safer).

Smart pointers exist for a reason: to help programmers do great programs without having to care too much about handling allocation/deallocation.

like image 35
ereOn Avatar answered Dec 19 '22 04:12

ereOn