How to pass objects to functions in C++?

后端 未结 7 888
無奈伤痛
無奈伤痛 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

    There are several cases to consider.

    Parameter modified ("out" and "in/out" parameters)

    void modifies(T ¶m);
    // vs
    void modifies(T *param);
    

    This case is mostly about style: do you want the code to look like call(obj) or call(&obj)? However, there are two points where the difference matters: the optional case, below, and you want to use a reference when overloading operators.

    ...and optional

    void modifies(T *param=0);  // default value optional, too
    // vs
    void modifies();
    void modifies(T ¶m);
    

    Parameter not modified

    void uses(T const ¶m);
    // vs
    void uses(T param);
    

    This is the interesting case. The rule of thumb is "cheap to copy" types are passed by value — these are generally small types (but not always) — while others are passed by const ref. However, if you need to make a copy within your function regardless, you should pass by value. (Yes, this exposes a bit of implementation detail. C'est le C++.)

    ...and optional

    void uses(T const *param=0);  // default value optional, too
    // vs
    void uses();
    void uses(T const ¶m);  // or optional(T param)
    

    There's the least difference here between all situations, so choose whichever makes your life easiest.

    Const by value is an implementation detail

    void f(T);
    void f(T const);
    

    These declarations are actually the exact same function! When passing by value, const is purely an implementation detail. Try it out:

    void f(int);
    void f(int const) { /* implements above function, not an overload */ }
    
    typedef void NC(int);       // typedefing function types
    typedef void C(int const);
    
    NC *nc = &f;  // nc is a function pointer
    C *c = nc;    // C and NC are identical types
    

提交回复
热议问题