C++: Reasons for passing objects by value

前端 未结 8 1358
清酒与你
清酒与你 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:42

    When passing by reference there is an inherit danger that you could inadvertently change the value passed to the method, inside the method. After the method call you could assume the method didn't change the object, when in fact it did.

    Passing by value has the negative aspect of extra memory required (and possibly a slight performance overhead) because you make a copy of the object you are passing in, but with the benefit that you can be sure your object passed into the method will not be modified inside the method.

提交回复
热议问题