Tuesday, July 14, 2009

Take parameters appropriately by value C++

Summary
Parameterize well: Distinguish among input, output, and input/output parameters, and between value and reference parameters. Take them appropriately.
Discussion
Choosing well among values, references, and pointers for parameters is good habit that maximizes both safety and efficiency.
Although efficiency should not be our primary up-front concern , neither should we write needlessly inefficient code when all other things, including clarity, are equal.


Prefer to follow these guidelines for choosing how to take parameters. For input-only parameters:
Always const-qualify all pointers or references to input-only parameters.
Prefer taking inputs of primitive types (e.g., char, float) and value objects that are cheap to copy (e.g., Point, complex) by value.
Prefer taking inputs of other user-defined types by reference to const.
Consider pass-by-value instead of reference if the function requires a copy of its argument. This is conceptually identical to taking a reference to const plus doing a copy, and it can help compiler to better optimize away temporaries.
For output or input/output parameters:
Prefer passing by (smart) pointer if the argument is optional (so callers can pass null as a "not available" or "don't care" value) or if the function stores a copy of the pointer or otherwise manipulates ownership of the argument.
Prefer passing by reference if the argument is required and the function won't store a pointer to it or otherwise affect its ownership. This states that the argument is required and makes the caller responsible for providing a valid object.

Artikel yang Berkaitan

0 komentar:

Post a Comment