Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ functions and methods style

Tags:

c++

For example, we have a function and its result is an array. I often see something like this:

void func(some_args, result_array){//some code//} 

So as you can see the function does not return the array and we pass it as an argument.

The second case looks like this:

float* func(some_args){ //some code// return result_array;}

Is there any convention about that or this is just about personal preferences? Personally I noticed that the second declaration, which returns an array, is very rare. Are there any reasons for that?

UPD: I'm sorry for being imprecise. Of course, I implied a pointer to an array in the second case.

like image 237
Max Avatar asked Mar 12 '23 08:03

Max


1 Answers

The difference is ownership.

void func(some_args, float*);

vs

float* func(some_args);

In the first form, it's very clear who is responsible for providing the memory for the array. In the second cause there is ambiguity: does the function you called own the memory or is it being transferred to you. Who is responsible for delete[]ing it?

char* s = strdup("hello");
// I have to remember to 'free()' what was strdup'd
// but what if I think "this is C++" and delete[] it?

-- Edit --

This may have contributed in part to the evolution of C++11s smart pointers (std::unique_ptr and std::shared_ptr), so the better option than the two discussed would be the use of one of those.

std::unique_ptr func(some_args);

This explicitly states "I'll return you a thing that you become responsible for".

like image 54
kfsone Avatar answered Mar 16 '23 00:03

kfsone