Effective std::string and c-string handling.
Code:
void test (std::string& test)
{
;
}
// this won't work
test ("hello");
// this will, but is it ugly?
test (String ("hello"));
The above won't work because "hello" is a c-string and not a std::string reference.
So, I have a number of functions like the above that try to speed up std::string handling by taking references... however... now I need to overload all my functions so that they can handle std::strings and c-strings separately.
Is there any way to be able to handle std::strings and c-strings efficiently without creating tonnes of overloaded functions? Do I just need to make up my mind and not support both everywhere?
Re: Effective std::string and c-string handling.
Yes, change your function signature to take a const reference:
Code:
void test (const std::string& test)
{
;
}
Viggy
Re: Effective std::string and c-string handling.
Quote:
Originally Posted by
MrViggy
Yes, change your function signature to take a
const reference:
Code:
void test (const std::string& test)
{
;
}
Viggy
Thanks!
Why was does making it const allow the conversion?
Re: Effective std::string and c-string handling.
Because it's a reference, it's possible for you to modify the object inside the function. Temporary objects are cannot (and should not) be modified. By passing a character array, as you are, the compiler has to make a temporary std::string to be used in the function.
Making the reference const, you're making it non-modifiable in the function, therefore the compiler happily creates the temporary object for you.
Viggy