C++: Reasons for passing objects by value

前端 未结 8 1357
清酒与你
清酒与你 2021-01-06 12:37

In Java, all variables containing proper objects are actually references (i.e. pointers). Therefore, method calls with these objects as arguments are always \"by reference\"

8条回答
  •  爱一瞬间的悲伤
    2021-01-06 12:47

    ALWAYS use pointers when using objects as arguments

    No, in C++ always pass by reference, unless your function can be called with nullptr as a valid argument. If the function does not need to modify the argument, pass by const reference.

    Passing arguments by value has several uses.

    If your function needs to create a copy of the argument it is better to create this copy by passing by value rather than creating a copy within the function. For instance:

    void foo( widget const& w )
    {
      widget temp( w );
      // do something with temp
    }
    

    Instead use

    void foo( widget w )  // copy is made here
    {
      // operate on w itself
    }
    

    Doing this also has the benefit of allowing the compiler to move widget if possible, which is generally more efficient than creating copies.

提交回复
热议问题