问题描述:

Possible Duplicate:

how to “return an object” in C++

Let there be a function func_foo that can do some computation on a given set of data and after crunching some numbers, comes up with a result that needs to be given back to the caller. Is there any reward (performance wise) in passing the pointer to result variable and it getting modified in the function vs. the function returning the value - other than the convenience/practicality with Char* and structures type results.

I did a preliminary search for this query prior to posting the question and couldn't find anything related. If a relevant discussion exists please do point me to it.

网友答案:

As is the common advice, code it the way that's easiest to read. Change from that way only if profiling shows it's a bottleneck.

Unless you intend to return a big struct, which might require copying, the difference is tiny. Even in the big struct case, if the compiler is clever, the two can turn out to be essentially equivalent when you look at generated code.

Most compilers use a register to return values that fit in a register, and this is very fast. So for such values I can't imagine a case where using a pointer to return value is an advantage.

Finally, it is a common C convention to return an error code as the function value. So it's also common to use pointers to memory to return values in this case. APIs that use this convention tend to be uniform and consequently easy to use.

Very simple example:

struct list_s {
   int size;
   struct element_s *array;
}

int initialize_list(struct list_s *list, int size)
{
   int err_code = 0;

   // do the intialization of *list, setting err_code if something goes wrong
   list->array = malloc(size * sizeof(struct element_s));
   if (list->array)
     list->size = size;
   else {
     size = 0;
     err_code = ERR_OUT_OF_MEMORY;
   }

   return err_code;
}
相关阅读:
Top