own string class

Started by
5 comments, last by snk_kid 19 years, 2 months ago
If you have to make an string class (char* wrapper), would you use a method length that every time you need the length of the string it counts the chars, or you would add a len member variable with updated length of string, and the length method only return this variable? And, would you make an empty constructor, that reserve a default quantity of memory for a string, or only a constructor from a char* string, and a copy constructor ? thanks
Advertisement
std::string is what u want to look at.

It allocates a reserved memory slice and most likely increments an internal value for the length. It would be more computationally expensive to loop and count each time .length() is called.

ace
I'd go the route of the variable.
Your length should be cached if it's used often enough. Just change it whenever the string changes. Also you should only allocate memory whenever there is something to store (which means don't allocate anything in a default constructor). Keep track of how much memory is currently allocated so you know when to allocate more depending on what the string changes to.

Lastly, unless you're doing this for an assignment or for learning purposes, use std::string.
I know std::string is a complete class for manage strings, and that its standart and well tested. I am only doing this for learning purposes, I have much time to waste! :)
I'd make your length a member variable, so you don't need to calculate it every time you call .length(). Bear in mind that in this loop: for(int i=0; i<str.length(); ++i), the str.length() call is made every loop itteration.

Also, I'd make the default constructor set the data pointer to NULL, and check for NULL in your c_str() equivalent function (get a const char* from your string class). E.g: const char* CString::c_str() const {return m_pData ? m_pData : "";}
Here are some things to consider, make you string type really a handle to a private reference counted representation:

Reference Counting - Part I.
Reference Counting - Part II
Reference Counting - Part III

all parts use custom string type for the articles using a technique that virtually all implementators of std::basic_string use, its known as copy on write (COW), the last article talks about the issues of COW in multi-threaded enviroments.

Something you may also want to consider, if you decide to overload the binary operators such as "+" for string concatenation your most likely implementation will be a naive one, google up on "composition closure objects" AKA "compositors" and its bigger brother expression templates (although for common custom string types, compositor types is all you need), you probably wont gain much from it if your using COW because you can see both techniques as a form of "lazy evaluation".

This topic is closed to new replies.

Advertisement