C++: Reasons for passing objects by value

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

    You normally pass by value because something is a value and should act like a value. In many cases passing by const reference is close enough to the same to be worth considering. In other cases, it's not.

    Passing by value can also be an optimization. At least IMO, this more or less secondary, but it can be important anyway (especially in choosing between passing by const reference and passing a real value.

    IMO, the real question should be in the opposite direction: why should the compiler pass a reference when you've clearly told it to pass a value? The answer is "premature optimization". The designers of Java (to mention your example, though it's hardly unique in this) decided that they knew better than to let the compiler do what it was told. Since passing a large object by value can be slow and might be a mistake, they decided to not let it happen at all, even though it can be fast and may well be exactly what was intended.

提交回复
热议问题