C++: Reasons for passing objects by value

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

    in Java, a reference is a garbage-collected "smart pointer".

    C++ also uses the concept of smart pointers, which are in the library, called unique_ptr and shared_ptr. shared_ptr is reference-counted so can be used in the same way as Java References. unique_ptr is similar, except is noncopyable and a little more lightweight. The benefit of both is never ever needing to use the delete keyword, and being able to rely on "pointers" which are protected by exceptions.

    C++ also supports the concept of a reference - which is usually a good choice for passing objects around (And even better is reference-to-const). References in C++ are bound to the type of object which is passed, so you need to specify (using the reference symbol &) in the function signature

    #include 
    
    void foo(std::string& bar)
    {
        bar = "world";
    }
    
    void foo2(const std::string& bar)
    {
        //passed by reference, but not modifyable.
    }
    
    int main()
    {
        std::string str = "hello";
        foo(str);
        foo2(str);
    }
    

    As for "raw" pointers - you can nearly always avoid them by using either a smart pointer, a reference, an iterator, or pass-by-value. plain ordinary pointers come with a mixed bag of "gotchas" which C++ inherited from the C language - if you've got a fairly recent compiler you should never really need to use them at all (unless you're going to be doing things like re-inventing the wheel for learning purposes with memory management, data structures, etc.)

提交回复
热议问题