How to pass objects to functions in C++?

后端 未结 7 892
無奈伤痛
無奈伤痛 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 04:58

    Pass by value:

    void func (vector v)
    

    Pass variables by value when the function needs complete isolation from the environment i.e. to prevent the function from modifying the original variable as well as to prevent other threads from modifying its value while the function is being executed.

    The downside is the CPU cycles and extra memory spent to copy the object.

    Pass by const reference:

    void func (const vector& v);
    

    This form emulates pass-by-value behavior while removing the copying overhead. The function gets read access to the original object, but cannot modify its value.

    The downside is thread safety: any change made to the original object by another thread will show up inside the function while it's still executing.

    Pass by non-const reference:

    void func (vector& v)
    

    Use this when the function has to write back some value to the variable, which will ultimately get used by the caller.

    Just like the const reference case, this is not thread-safe.

    Pass by const pointer:

    void func (const vector* vp);
    

    Functionally same as pass by const-reference except for the different syntax, plus the fact that the calling function can pass NULL pointer to indicate it has no valid data to pass.

    Not thread-safe.

    Pass by non-const pointer:

    void func (vector* vp);
    

    Similar to non-const reference. The caller typically sets the variable to NULL when the function is not supposed to write back a value. This convention is seen in many glibc APIs. Example:

    void func (string* str, /* ... */) {
        if (str != NULL) {
            *str = some_value; // assign to *str only if it's non-null
        }
    }
    

    Just like all pass by reference/pointer, not thread-safe.

提交回复
热议问题