If you don't mind me asking, is there a particular reason why you aren't able to use the standard [tt]string[/tt] class, and if so, is there a reason you aren't you writing it as a subset of the standard class (i.e., some of your classes don't match the standard ones)? Any answer is legitimate, but knowing the purpose might help us with understanding the goals.
One of the more serious problems I see is with memory leaks; not surprising, as those are one of the largest headaches in C++ for anyone. You really have to ensure that any memory you allocate gets deallocated later.
I would seriously consider using a [tt]length[/tt] instance variable and dropping the zero-delimiting. While this would mean you couldn't use the standard c-string library, and that you'd have to do a bit of fiddling about in your [tt]text()[/tt] method (BTW, the name for this function in the standard [tt]string[/tt] class is [tt]c_str()[/tt]), it would save some headaches in other places. Even if you use zero-delimited strings, I would still have a length variable. The size isn't going to change, after all (except perhaps in the assignment operator, though I recommend a way to avoid it even there below), and while it takes up an extra four bytes or so of space, it avoids the repeated [tt]strlen()[/tt] calls, which is a Good Thing. When you
do use the standard c-string function, I would recommend using the
n variants ([tt]strncpy()[/tt], strncat()[/tt], etc); once again, you already know the sizes of the strings, so you might as well take advantage of that for a bit of extra safety.
I agree with Colonel Kernel about making the concatenate operator a friend function rather than a method, mainly because you are not changing the existing objects, but creating a new one. I would use your existing constructor to handle the actual object creation.
This brings up an important point: any concatenation operator that isn't passed an intermediate buffer to fill must dynamically generate the concatenated string as a new string object. This would have to be returned as a string pointer or a string reference, not a string per se.
Regarding the copy constructor, I disagree with CK here. You don't want to do the copying in the assignment method; rather, you will want to create an actual copy constructor (that is, a constructor that takes an object of the same class and creates a second duplicate object) and then create a friend assignment operator using that:
Code: Select all
// this assumes your current class design
// note that in a copy constructor, the
// argument *must* be a ref variable
string::string(string& src)
{
if (NULL == src.str)
{
str = NULL;
}
else
{
int len = src.length() + 1;
str = new str[len];
strncpy(str, src.str, len);
}
}
You'll probably want a comparison operator as well, both for your [tt]string[/tt] objects and for c-strings.