C++: Reasons for passing objects by value

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

    You're wrong in that you should pass by pointer. If you want to pass by reference, well... simply pass by reference:

    void foo(int& x)
    {
       x = 3;
    }
    
    int main()
    {
       int a = 0;
       foo(a);
       assert( a == 3 );
    }
    

    Also, note that passing by value guarantees that the your variable can't be changed inside the called context. Although so would passing by const reference...

提交回复
热议问题