Possible Duplicate:
FAQ: How to pass objects to functions in C++?
Pointer vs. Reference
Hi all,
in c/c++,
we can pass a object as call by reference or passing pointer of the object.
for example:
i want to create a function which will take string vector as input and output a map that contains some value for each string. the return value of the function is bool, which indicate success or failure.
function (call by reference)
bool calculateSomeValue( vector<string> input, map<string, double>& result)
{
//// bla bla bla
return true/false;
}
function (using pointer )
bool calculateSomeValue( vector<string> input, map<string, double>* result)
{
//// bla bla bla
return true/false;
}
which one is best? does any one have any idea of the pros and cons of these two options?
thanks in advance.
This is a matter of style. At Google (see Google C++ style guidelines), the following would be preferred:
This is because using a pointer requires the explicit use of an ampersand at the call site:
As opposed to the way it would be invoked with a reference type:
By forcing the use of an ampersand in cases where parameters are modified, it is clear at the call site what will happen. When using references, it becomes necessary to lookup the documentation for each and every function to know whether it has the potential to modify its input parameters.
However, the use of a pointer has its downsides, too. In particular, the use of a pointer means that you shift responsibility of handling null from the caller where the pointer would be dereferenced (if the variable is a pointer and not merely an address-of expression with a local variable) to the function. That is, when using a pointer type,
CalculateSomeValueneeds to check fornullptr(or needs to clearly document that it requires this checking in the caller), whereas the use of a reference type is self-documenting and clearly indicates that a non-null reference is expected.For this particular situtation, I personally highly recommend a hybrid approach:
… where
Output<T>is created by a function with the signature:… and where
Output<T>overloads operators->,*, etc. This basically forces the call sites to be explicit in the fact that the input will be mutated by requiring:… as opposed to:
… while simultaneously gaining the non-null semantics/syntax of references.