I’m working on writing my own string class and am having trouble with overloading the += operator for a MyString being +=’d to a char. I figured this would work but with no luck. Here’s the implementation I tried. Any assistance on getting it to work correctly will be much appreciated.
MyString& MyString::operator +=(char c)
{
char derp[1] = {c};
strcat(value, derp);
return *this;
}
This is not going to work for several reasons:
derpis not a null-terminated array, which it has to be if you pass it as a parameter tostrcatvaluerepresents can actually hold more data; neither is there a facility to make sure that the buffer is always null-terminated (which again it needs to be because you are passing it tostrcat)\0as part of a string value because that will be mistaken for a null terminator; in technical terms, your string class would not be “binary safe”; to fix this you need to dropstrcatand similar functions entirely and switch tomemcpyand friendsApart from the above, overloading
operator +=like this allows for code such asFinally, the
str***family of functions is going to get needlessly slower as your strings are getting larger (because they have to scan the string from the beginning each time in order to determine where it ends). Keeping your own length variable and switching tomem***is going to fix this issue as well.