Junior
What is the name of the workaround for passing a value instead of a reference in C/C++?
sobes.tech AI
Answer from AI
Passing by value using references to constant objects.
void process_value(const MyObject& obj) {
// Working with obj as if it were passed by value
// (changes are impossible due to const),
// but avoiding copying a large object.
// This function CANNOT modify the state of the object referenced by obj.
}
// Example usage:
MyObject large_object;
process_value(large_object); // large_object is not copied
Advantages over passing by value:
- No costly copying of large objects, which improves performance.
- Preserves the semantics of passing by value in terms of immutability within the function.
Disadvantages compared to passing by value:
- Requires special syntax
const &in the function signature. - If the object is very small (e.g., a primitive type like
int), passing by value may be faster due to potential overhead of dereferencing the reference.