-
March 9th, 2010, 05:30 PM
#1
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?
-
March 9th, 2010, 05:37 PM
#2
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
-
March 9th, 2010, 05:38 PM
#3
Re: Effective std::string and c-string handling.
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?
-
March 9th, 2010, 05:42 PM
#4
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|