Using a smart pointer to manage memory allocated inside a function

Background

If I had a foo function as follows

 void foo(std::vector<int>& values) { values = std::vector<int>(10, 1); } 

Then I could call him

 std::vector<int> values; foo(values); 

Note that the initial vector empty, then it is filled inside the foo function.

I often come across interfaces that I cannot change (i.e. third-party) that have the same intentions as above, but using raw arrays like

 void foo(int*& values) { values = new int[10]; std::fill_n(values, 10, 1); } 

My problem is that now I am responsible for managing this memory, for example

 int* values; foo(values); delete[] values; 

Question

Is there a way to use smart pointers to manage this memory for me? I would like to do something like

 std::unique_ptr<int[]> values; foo(values.get()); 

but get returns a pointer that is the value of r, so I cannot pass it using a link other than const.

+5
source share
2 answers
  • Create an empty unique_ptr.
  • Create a pointer.
  • Pass a pointer to a function.
  • Reset unique_ptr to this pointer.

Like:

 std::unique_ptr<int[]> values; int* values_ptr; foo(values_ptr); values.reset(values_ptr); 

Or:

 int* values_ptr; foo(values_ptr); std::unique_ptr<int[]> values(values_ptr); 
+2
source

The simple answer is: you cannot. But I believe that there is a way to simplify your life. Since you always do the same, you just need to write a function that will do it for you, and call that function when you need to. Since I assume that you want to use the return value stored in memory before freeing it, I will return its function.

 template <typename T, typename Function> std::unique_ptr<T[]> call(Function f) { T * value; f(value); return { value }; } // then to use it auto value = call<int>(foo); 

Does this suit you?

The function can be improved to detect the difference for pointers to a single object or array if you need it, and probably you could also improve the automatic determination of the required type of parameter so that you do not have to enter it.

+1
source

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


All Articles