简体   繁体   中英

c++ const argument passing: why compilers do not automatically set to pass-by-reference

I learnt that for non-primitive-type constant arguments it is more efficient to pass them into functions as references than as values:

  • not efficient version:

    void funcA(const std::string myString)

  • efficient version:

    void funcA(const std::string& myString)

Since the efficient version seems to be an obvious choice, I wonder why C++ compilers do not just automatically optimize this way for the not-efficient version?

There are optimizations even in case of copies . Yes, in general, the compiler is required to make a copy when a function parameter is passed by value (so there is no connection between the local copy and the outside (original) object) . Compiler is also allowed to elide the copy , means to use the original object itself, when the source is an rvalue.

Don't copy your function arguments. Instead, pass them by value and let the compiler do the copying. - cpp.next.com

"By value" and "by reference" have difference of semantic nature . And the "optimization" we get from passing by reference is more of a consequence then a destination, one that is derived from the logic and meaning of the we express in the program.

Also, consider that even if in this scope the reference is const , we still have a reference (to another, independent object). Means that this object can still be modified by some external (to our scope) forces.

In the end, we should first strive for clarity of our expressiveness in the language, not to seek premature optimizations .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM