C++ Programming Tips: Using Constant References Instead of Value Passing

1. Benefits of Passing by Constant ReferenceIn C++, it is well-known that using constant references for function parameters instead of value passing can avoid the overhead of construction and destruction, thereby improving runtime efficiency.The benefits go beyond this; passing by reference can also prevent object slicing issues. (This issue was also mentioned in “C++ Programming Tips: Differences Between Exception Handling and Function Parameter Passing”)

class People{};class Student : public People{};void Test(People people){}void Run(const People& people){}Student stu;// At this point, there is only one People object in the function// All member functions of the object use the People version of Test(stu);// At this point, there is only one Student object in the function// All member functions of the object use the Student version of Run(stu)

2. What Types Can Use Value PassingMany people believe that using value passing for built-in types like int and small classes does not incur much overhead. In fact, this is true for built-in types like int, but small classes are an exception.A small class may contain pointers to large data, and the overhead of deep copying can be significant.Moreover, the compiler does not optimize user-defined small classes in the same way it does for built-in types, which is another issue with small classes.Finally, the size of user-defined small classes can easily change with updates; once they become particularly large, no one would want to change from value passing to constant reference passing.Therefore, it is still recommended to use constant references for small classes. So, aside from built-in types, are there any other types suitable for value passing?Yes, STL iterators and function objects are suitable. The reason for this relates to their design rules, where the designers are responsible for ensuring their efficiency and immunity to slicing issues.In summary, only built-in types, STL iterators, and function objects are suitable for value passing.

Leave a Comment