const Return Types
Let’s learn about the kinds of variables a function can return.
We'll cover the following
A function can return values, references, and pointers, and all of these can be const
. However, does it make sense to convert them to const
? Let’s find out!
Returning const
objects by value
The first-time const
users might get enthusiastic about turning everything into const
and might start converting signatures like std::string getName()
into const std::string getName() const
. However, it’s not a great idea to turn all the return values into const
.
Why is that so?
The const
qualifier shows the reader and compiler that something should not be modified. When we return something by value, it makes a copy for the caller.
Does it make sense to make a copy const
?
Imagine buying a house, and not being allowed to modify it. In most cases, you want your house to be your castle. It is similar to the relationship between our copy and our object. We want to be able to do whatever we want to the copy.
A const
object doesn’t make sense when it is returned by the value. It’s misleading and might even be harmful.
How can it be harmful?
Move for non-const
return types
The move is possible for non-const
return types. Let’s say we have the following code:
Get hands-on with 1400+ tech skills courses.