Multiple Parameters
Parameter Passing Efficiency
Each parameter passed by value creates a copy. For large objects, this can be costly. General guidelines:
1. Primitive types (int, char, etc.): pass by value
2. Small structs: pass by value or const reference
3. Large objects: pass by const reference
4. Output parameters: pass by non-const reference (or prefer returning values where appropriate)
ℹ️ Note: If a function needs its own copy (e.g., to store), taking by value and std::move-ing into a member can be efficient for movable types.
Type | Size | Recommended Passing |
---|---|---|
int, float, bool | Typically small (≤8 bytes) | By value |
Small struct | ≤16 bytes | By value or const reference |
std::string | Implementation-defined (~24–32 bytes with SSO) | By const reference |
Large class | >32 bytes | By const reference |
Parameter Order Matters
Organize parameters from most significant to least significant. Place optional parameters at the end:
⚠️ Warning: Default arguments must be provided from right to left. Once a parameter has a default, all parameters to its right must also have defaults.
Example
#include <string>
enum class Color { Red, Green, Blue };
enum class Shape { Circle, Square, Triangle };
// Poor order (invalid: defaulted parameter before non-defaulted)
// void draw(int thickness = 1, Color color, Shape shape);
// Better order
void draw(Shape shape, Color color, int thickness = 1);
Alternative Approaches
When functions require many parameters, consider:
1. Parameter objects: Bundle related parameters in a struct
2. Builder pattern: Chain method calls to configure options
3. Named parameters idiom: Use temporary proxy objects for readability
Example
#include <string>
enum class Color { Red, Green, Blue };
enum class Shape { Circle, Square, Triangle };
// Parameter object example
struct DrawParams {
Shape shape;
Color color;
int thickness = 1;
bool antialias = false;
};
void draw(const DrawParams& params);