Jump to content
  • Advertisement
Sign in to follow this  
d000hg

Remind me about compatibility between std::string & const char *

This topic is 4236 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a function:
vector<string> split(const string & str, const string delim);
You use it like:
split(string("My name is John")," "); //you get a vector with each word as an entry
string str("abc-123.XXX"), delim("-.");
split(str,delim); //you get a vector "abc","123","XXX"
I can't remember (and don't have a compiler handy) how this will cope if I use it like that. It has to accept string objects, but delim has to accept string objects and string literals. I think that means delim can't be a refernce as when you pass in " " it breaks? So how many overloads do I need to write?
vector<string> split(const string & str, const string delim);
vector<string> split(const string & str, const char *);

Share this post


Link to post
Share on other sites
Advertisement
Delim could also be passed by const reference or char, but how about the obvious use of templates here? This is my split function:


typedef std::vector<std::string> strings;
...
template<typename T>
const strings& split(const std::string& pStr, const T& pDelim)
{
static strings buf;
buf.clear();
size_t _first = 0;
size_t _last = 0;

while (_first != std::string::npos)
{
_first = pStr.find_first_not_of(pDelim, _last);
if (_first == std::string::npos) break;
_last = pStr.find_first_of(pDelim, _first);
buf.push_back(pStr.substr(_first, _last-_first));
}
return buf;
}



Works with anything you can throw at string::find_first_of(), which are all character and string types and references to them.

Share this post


Link to post
Share on other sites
You don't need any overloads, the std::basic_string template class has an non-explicit constructor for a character pointer:

basic_string( const charT * s, const Allocator & a = Allocator() );


jfl.

Share this post


Link to post
Share on other sites
Yup, taking a const std::string& will work in the case you describe.

I think one of the few really tricky things to look out for when interfacing std::string with const char* is that if you do something like this:


const char *getSomeString() { ... }

...

std::string s = getSomeString();



and getSomeString happens to return NULL, your application will crash horribly.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!