Here is two variants. First:
int n = 42;
int* some_function(int* input)
{
int* result = new int[n];
// some code
return result;
}
int main()
{
int* input = new int[n];
int* output = some_function(input);
delete[] input;
delete[] output;
return 0;
}
Here the function returns the memory, allocated inside the function.
Second variant:
int n = 42;
void some_function(int* input, int* output)
{
// some code
}
int main()
{
int* input = new int[n];
int* output = new int[n];
some_function(input, output);
delete[] input;
delete[] output;
return 0;
}
Here the memory is allocated outside the function.
Now I use the first variant. But I know that many built-in c++ functions use the second variant.
The first variant is more comfortable (in my opinion). But the second one also has some advantages (you allocate and delete memory in the same block).
Maybe it’s a silly question but what variant is better and why?
I think second variant is better, because you have “balanced responsibility over pointer”. That makes code more readable, because you see where you allocate and where you free your memory.
If you want to use first variant, I’d suggest you to make dual funnction
some_function_free(). As formalloc/free,new/delete,new[]/delete[], etc. Even that it will do simpledelete[], by using this you’ll save time when you’ll want to change the way you allocate memory.