is there any specific case where pass-by-value is preferred over pass-by-const-reference in C++?

后端 未结 15 1888
臣服心动
臣服心动 2020-12-06 08:03

I read that they are conceptually equal. In practice, is there any occasion that

foo(T t) 

is preferred over

foo(const T&         


        
相关标签:
15条回答
  • 2020-12-06 08:28

    The reason pass by const reference and by value are conceptually the same is that neither can modify the original.

    Normally, I am big fan of pass by value because it creates code that avoids many of the complexities that occur when multiple threads are sharing access to common data.

    That said, it does potentially make you're code slower. My take in the past has always been to prefer pass by value unless I know their is (or will be) a performance problem by doing so. I may have to modify this slightly to include pass by const reference as an even better option.

    0 讨论(0)
  • 2020-12-06 08:30

    If the object being passed is a smart pointer (i.e. it does its own reference counting) then passing by value might be more reasonable.

    I realize that's sort of a sideways answer to your question - the object wrapped by the smart pointer is not copied when passed by value, so it's more similar to passing by reference in that case. Nevertheless, you don't need "by reference" semantics in this case.

    There is a problem with my line of reasoning so far, though - you'll lose the "const-ness" of the argument by passing by value. Perhaps you should just use the "by reference" semantics after all...

    0 讨论(0)
  • 2020-12-06 08:30

    They're not conceptually equal at all...

    The former creates a copy of the object inside the function. This implies that the value can be modified in the function safely. It also implies that a full copy of the object occurred, which can be a problem if the object is large.

    The latter creates an alias to the object and states that it cannot be modified within the object. No copying occurs, but each access to the object inside the function will require a dereference. The compiler takes care of this for us, but it's still important to know.

    The difference becomes very important if you have a type that is normally passed in registers. For example, integers, floating point numbers, and even 4-float vectors on some platforms. Performance concerns dictate that you want to object to stay in a register for as long as possible without writing itself back to memory, and pass by value makes this much more likely.

    So for basic types (char, short, int, long, float, double), you should always prefer pass by value unless you specifically need to use a reference to store a value for use after the function exits. For full objects, generally prefer to pass by const reference.

    0 讨论(0)
提交回复
热议问题