Before I give an answer to your question (you find it at the end of this post), here's a brief summary of the possibilities you have for passing arguments to a function:
1. Copy-constructed objects (pass-by-value):
void cp(point p);
This is pass-by-value. A temporary point
object is created and copy-constructed from whatever point
object you pass into cp
. Once execution leaves the cp
function, the temporary object is destroyed.
Note that because the function operates on a copy of whatever was passed to the function, you can modify that local point
object as much as you want, the original object of the caller will not be affected. There's no way to change this behaviour with pass-by-value parameters.
2. References to objects (pass-by-reference):
void cp(point& p);
This is pass-by-reference. The actual object passed to the function is available (and potentially subject to modification) inside the function. If you don't want the function to be able to change the passed-in object, declare the parameter as const point&
:
void cp(const point& p);
3. Pointers to objects (pass-by-reference):
void cp(point* p);
This is also pass-by-reference, with a few subtle differences. One notable difference is that you can pass a null pointer to the function. This is not possible with references, because references must be initialized and cannot be reseated afterwards. -- As with references, if you want to disallow cp
from changing the passed-in point
, declare it as const:
void cp(const point* p);
Answer to your question:
Pass-by-value parameters are not inherently bad in any way. Of course, there are types for which copy construction is expensive (e.g. very large or complex objects), or where it has certain side effects (e.g. with std::auto_ptr
). In these cases, you should be careful. Otherwise, it's just another feature of C++ which has its perfectly reasonable uses.