How to pass objects to functions in C++?

后端 未结 7 886
無奈伤痛
無奈伤痛 2020-11-21 04:55

I am new to C++ programming, but I have experience in Java. I need guidance on how to pass objects to functions in C++.

Do I need to pass pointers, references, or no

7条回答
  •  借酒劲吻你
    2020-11-21 05:13

    Rules of thumb for C++11:

    Pass by value, except when

    1. you do not need ownership of the object and a simple alias will do, in which case you pass by const reference,
    2. you must mutate the object, in which case, use pass by a non-const lvalue reference,
    3. you pass objects of derived classes as base classes, in which case you need to pass by reference. (Use the previous rules to determine whether to pass by const reference or not.)

    Passing by pointer is virtually never advised. Optional parameters are best expressed as a std::optional (boost::optional for older std libs), and aliasing is done fine by reference.

    C++11's move semantics make passing and returning by value much more attractive even for complex objects.


    Rules of thumb for C++03:

    Pass arguments by const reference, except when

    1. they are to be changed inside the function and such changes should be reflected outside, in which case you pass by non-const reference
    2. the function should be callable without any argument, in which case you pass by pointer, so that users can pass NULL/0/nullptr instead; apply the previous rule to determine whether you should pass by a pointer to a const argument
    3. they are of built-in types, which can be passed by copy
    4. they are to be changed inside the function and such changes should not be reflected outside, in which case you can pass by copy (an alternative would be to pass according to the previous rules and make a copy inside of the function)

    (here, "pass by value" is called "pass by copy", because passing by value always creates a copy in C++03)


    There's more to this, but these few beginner's rules will get you quite far.

提交回复
热议问题