double average(double a, double b);//call-by-value;
void swap(double &a,double &b);//call-by-reference. in C++11, this is more technically call-by-lvalue-reference.
string randomItem(const vector<string>&arr);//call-by-reference-to-a-constant. const reference. call-by-constant reference.
the paramerter- passing mechanism for c++ prior to c++11 can thus generally be decided by a two part test;
-
If the formal parameter should be able to change the value of the actual argument, then you must use call-by-reference.
-
Otherwise, the value of the actual argument cannot be changed by the formal parameter. if the type is a primitive type, use call-by-value, Otherwise, the type is a class type and is generally passed using call-by-constant-reference, unless it is an unusually small and easily copyable type(e.g., a type that stores two or fewer primitive types).
Put another way
-
Call-by-value is appropriate for small objects that should not be altered by the function.
-
Call-by-constant-reference is appropriate for large objects that should not be altered by the function and are expensive to copy.
-
Call-by-reference is appropriate for all objects that may be altered by the function.
C++11 adds rvalue reference: call-by-rvalue-reference. The central concept is that since an rvalue stores a temporary that is about to be destroyed. it can be implemented by a move instead of a copy. often moving an object's state is much easier than copying it, as it may involve just a simple pointer change.
string randomItem(const vector<string>&arr);//returns random item in lvalue arr
string randomItem(vector<string>&&arr);//returns random item in rvalue arr;