If I return the STL container from the function by value, will GCC copy all the elements separately?

If I have the following function declaration that returns a value std::list<Triangle*>by value:

std::list<Triangle*> getAllAbove(Triangle* t);

when I return std::list<Triangle*>(which is created on the stack in getAllAbove) at the end of getAllAbove, GCC will be able to optimize the call to the std::list<Triangle*>copy constructor (which is supposed to go through all the elements and copy them) or at least copy only the list metadata (for example, not the elements themselves) ? The list could potentially contain several thousand pointers, and I would like to avoid unnecessarily copying all of them.

The only way to get around the copy constructor call to create a list on the heap and then return a pointer to it?

+3
source share
5 answers

Well, an alternative way to get around copying is to use the idiom "return parameter" instead of using the return value of the function

void getAllAbove(Triangle* t, std::list<Triangle*>& result);

Instead of forming the result “on the stack”, as it is now, form it directly in the parameter result(that is, in the list of recipients that you pass from the caller).

As for your source code, whether copying will occur or not depends on the capabilities of your compiler.

. ( , , , .) -, , , . . ( , ++ 98).

, ( ++ 03). , , "return parameter". , GCC . , .

+6

, , : ? .

+4

, . . , , , , .

, , , . , , , ( ) .

+2

, list<> .

std::list<Triangle*>& getAllAbove(Triangle* t, std::list<Triangle*>& myList);

, .

0
source

You can go with void getAllAbove(Triangle* t, std::list<Triangle*>& out). Fill out the list once and get the output inout

0
source

All Articles