In C++, function parameters (including method members) can be passed:
Example:
void foo(int value); // by value void foo(int* ptr); // by pointer void foo(const int& ref); // by reference (optimal for large objects!)
When passing by reference, optimization (copy elision) can be implemented, and for large objects, const & is recommended. For pointers, always check for nullptr.
What is the difference between
const MyClass& objandMyClass objin function parameters?
Answer:
const MyClass& does not copy the object, but only provides access without the ability to modify (optimal for large objects). MyClass obj always makes a copy, which is expensive for large sizes or when proper copying is not implemented (e.g., deep copy is not realized).
void process(const std::string& s); // Does not copy void process(std::string s); // Copies
Story In a corporate mathematical structures library, a programmer decided to speed up work by passing large containers by value. This caused significant overhead with each function call — performance decreased by half.
Story In the user management module, pointers were used without checking for
nullptr. Occasionally, random crashes occurred when accessing invalid pointers, debugging took months.
Story In an image processing project, some functions accepted objects by value, while others by reference. For one of the classes, deep copy was not implemented, causing memory leaks and implicit shared ownership of resources after passing by value.