Returning pointers from a class. Who is responsible for the removal?

I have a C ++ class that implements a binary compatible interface (which will be used as a shared library), thereby returning only C types. strings like const char *, void pointers, and pointers to other classes with a binary compatible interface. The question is how should I organize memory management, should I return constant pointers to existing class data (danger of using an obsolete pointer by the user) and allocate memory myself, or rather point to some heap variables and be the user's responsibility to delete these pointers later or ??? Are there any general recommendations for this?

+4
source share
7 answers

In a "binary compatible interface", using the C interface, you do not assume a common heap. Therefore, the side that allocates memory from the heap is the side that returns it to this heap.

You can get impressive crashes and / or silent damage if you select a block from one heap, pass it through the C interface, and then add the other delete side.

+5
source

Make the caller responsible for allocating and freeing memory.

+1
source

Both are accepted and used in production environments if they are clearly and thoroughly documented.

+1
source

It really is up to you.

A good object-oriented approach is for the class itself to manage memory. Most of the benefits of OOP are that it encapsulates functionality as best as possible. That way, you can create it in such a way that the code calls your class methods without worrying about how memory is allocated or freed, because it is controlled by the class.

However, there are times when this approach does not work, because there is no good way to find out the class when memory is no longer required. In these cases, you can either simply allocate memory to the caller (and then free it), or simply indicate that the caller must free the memory that was allocated and returned from the class.

This is done in both directions. There are no real hard rules.

+1
source

If possible, use smart pointers such as unique_ptr or shared_ptr. (Which should not be a problem since you are already wrapping C functions if I am right.)

0
source

I would say that the caller is responsible for releasing the data. Also note that you cannot use new if the caller is not a C ++ application.

0
source

If you are writing an existing API, then you are doing everything that this API requires. You have no choice in this matter; The API has who is responsible for what, and the code on the other side of the API expects your implementation to be consistent.

0
source

Source: https://habr.com/ru/post/1399198/


All Articles