Will the std :: string transition through copying be optimized?

Our project has many functions where strings are transmitted through a copy:

void f(std::string a); 

As we all know, it is more efficient to pass it by reference, but my colleague says that the compiler optimizes it anyway. Is this close to the truth for the GCC?

g ++ 4.8.2, -O2 is included in the Release build.

Thanks!

+5
source share
1 answer

This is a somewhat controversial issue.

Theoretically, yes, the compiler is more likely to apply certain optimizations when passing by value. Chandler Carrut explained how this works for LLVM in his BoostCon 2013 label Optimization of Emergent Structures C ++ (video) / (slides) .

The problem is that there is overhead for passing by value that the compiler cannot get rid of. This is true even if you have a compatible C ++ 11 compiler and a movable type like std::string . Herb Sutter discussed the challenge of conventions, in particular in his talk CppCon2014 "Fundamentals of the modern C ++ style (slides) . His conclusion is to do this as you studied in C ++ 98-school: use const& for default for passing non-trivial arguments.

Other important arguments regarding the default transition agreement is that it is very difficult to write efficient code that provides a strong guarantee of the security of the exception. To get efficiency, the user will have to move the line to the function. But in this case, if the function throws, the string leaves forever.

Of course, the basic optimization directive still applies: when in doubt, measure. Run the profiler on your real code to find out which one is best for you.

+6
source

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


All Articles