How was the "string" type created in C++? In C, strings are character arrays, but how did C++ turn the character arrays into the "strings" we know of in C++?
- Did you mean historic details ? Otherwise @Dave's answer is correct.iammilind– iammilind2011-07-26 04:54:13 +00:00Commented Jul 26, 2011 at 4:54
- @In silico - To be more specific, I am trying to figure out how instead of character array, a "string" can be defined. Does the compiler turn std::string into a character array at runtime? Finally, if not, how does it allocates the memory?Josh Bartholf– Josh Bartholf2011-07-26 05:01:40 +00:00Commented Jul 26, 2011 at 5:01
- 1@Josh Bartholf: You should edit that into your question so you can get more specific answers.In silico– In silico2011-07-26 05:06:40 +00:00Commented Jul 26, 2011 at 5:06
Add a comment |
3 Answers
The character array is still in there, it just has a class wrapped around it. Imagine something like this:
class String { private: char* stringData; public: String(const char* str) { stringData = new char[strlen(str)+1]; strcpy(stringData, str); } ~String() { delete[] stringData; } String& operator += (const String& rhs) { char* newStringData = new char[strlen(rhs) + strlen(stringData) + 1]; strcpy(newStringData, stringData); strcpy(newStringData + strlen(stringData), rhs); delete[] stringData; stringData = newStringData; return *this; } }; That's obviously a very incomplete example, but you get the idea, right?
The actual implementation of std::string is pretty comprehensive, but it's nothing you couldn't do yourself. Here's some differences in the official std::string class from what I posted:
- The length of the string is usually included as a member variable, so you don't have to keep calling strlen to find the length.
- The std::string class uses templates, so you're not limited to the char type. If you're using Unicode, you can use std::wstring, which uses 16- or 32- bit strings by replacing the char type with the wchar_t type.
- Usually there's lots of optimizations to choose from. Lately the most popular has been the "short string" optimization.
Once you've relatively comfortable with C++, you should try writing your own string class. It's not something you would use in practice, but it's a really good exercise for library writing.
3 Comments
Josh Bartholf
Thank you very much... This is exactly what I was trying to figure out. I guess I was making it more complex then I actually had to.
iammilind
+1, It's a good answer. Just use
delete[] for character arrays.Rick Yorgason
Oops! Thanks for catching that. It's so rare that I have to deal with manual memory allocation these days.