const Class Type Parameters
Learn about the const class type parameters and when they're best used.
For class types, there is a different general rule. If we take a class type parameter by value, we make a copy of it. In general, copying an object is more expensive than just passing a reference around.
So the rule to follow is not to take an object by value but by const&
. Reference to avoid the copy and const
so that the object doesn’t get modified.
We make local variables const
by default similarly, we should take references and pointers const
. If we want to modify the original object, we can take it by reference and omit the const
.
On the contrary, if we want to modify only the object in a local scope, we can take it by value as we will have to make a copy of it.
Make a copy
Don’t take an object by const&
if we are making a copy.
void doSomethingAndModifyLocally(const ClassA& foo) {
// ...
ClassA foo2 = foo;
foo2.modify();
// ...
}
In the above case, we should take foo
by value instead. We can spare the cost of passing around a reference and the mental cost of declaring another variable and calling the copy constructor.
Pass by value, if you need a local modification
If we modify an object only in a local scope, we should take it by value to make a copy of it.
void doSomethingAndModifyLocally(ClassA foo) {
// ...
foo.modify();
// ...
}
Get hands-on with 1400+ tech skills courses.