I know const
is used for a value that can't change
const
is used for anything that can't change - a value, a pointer, or a reference. It is a good idea to use const
in situations when something is not supposed to change, even if you pass it by value.
Why and when should you use this and not just a const string
?
const string&
is more economical, because it lets you avoid copying the content of the string. You should use it when the string
that you are passing to the function is guaranteed to remain in place for the duration of the function. This is always the case when you call a function directly.
In contrast, const string
should be used when there is a possibility that the string could be deleted while the function is still running.
For example, this could happen when you call a function on a different thread, and then delete the parameter that you passed to it, or let the parameter go out of scope. Trying to pass the parameter by const
reference would result in undefined behavior, while passing it by const
value would make a private copy, thus preventing UB.