Given these 2 functions that modify and return a string:
// modify the original string, and for convenience return a reference to it
std::string &modify( std::string &str )
{
// ...do something here to modify the string...
return str;
}
// make a copy of the string before modifying it
std::string modify( const std::string &str )
{
std::string s( str );
return modify( s ); // could this not call the "const" version again?
}
This code works for me using GCC g++, but I don't understand why/how. I'd be worried that 2nd function would call itself, leaving me with out-of-control recursion until the stack is exhausted. Is this guaranteed to work?
You have two overloaded functions:
std::string &modify( std::string &str )
std::string modify( const std::string &str )
What you're passing is a non const-qualified std::string
. Therefore, the function that takes the non const-qualified argument is a better fit. If that didn't exist, the compiler could convert the non const-qualified string to a const-qualified string to make the call, but for function overloading a call that requires no conversion is a better fit than a call that requires a conversion.
return modify( s ); // could this not call the "const" version again?
No. It is not recursion. It would invoke the other overload whose parameter is std::string &
.
It is because the type of the expression s
is std::string &
which matches with the parameter type of the other overloaded function.
In order to recurse, the argument at call-site needs to convert into std::string const &
. But in your case, this conversion is unnecessary as there exists an overload which doesn't require conversion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With