There are 4 issues with your code.
- Your assignment operator has the following line:
char* buffer = new char[len + 1];
This is declaring a new pointer variable and not using the class member. This will allocate memory to a pointer that then goes out of scope and can never be deleted and will be a memory leak and make your class not function.
- The lack of a destructor means that your class leaks memory. Your destructor is responsible for freeing the memory that your are allocating with
new[]
.
- The lack of a copy constructor means that your String class cannot be used in many situations including in an STL container. The STL containers require that types have a public copy constructor, assignment operator and desctructor.
- You are not enforcing your class invariants in the face of exceptions. The goal is to make your class exception safe. In the changes I made I tried to achieve the strong exception guarantee and conserve the class state in the face of exceptions. Considering exception safety is an important aspect of creating your own classes - especially library classes such as String.
Here's the code that attempts fixes all of those issues. To keep the code short I am putting the implementation into the class rather than separating it. Of course, in real code you should use std::string.
class String
{
public:
String() : len(0), buffer(nullptr)
{}
String(const char right[]) : len(0), buffer(nullptr)
{
if(!right)
return;
int temp_len = strlen(right);
buffer = new char[temp_len+1];
len = temp_len; // only set the length after the allocation succeeds
strcpy(buffer, right);
}
// a copy constructor is essential for this class
String(const String& right) : len(0), buffer(nullptr)
{
String temp(right.buffer);
swap(temp);
}
// must have a destructor to avoid leaks
~String()
{
if(buffer) // only delete if it has been allocated
delete[] buffer;
}
String& operator= (const String& right)
{
String temp(right.buffer);
swap(temp);
return *this;
}
int length() const
{
return len;
}
private:
void swap(String& rhs)
{
std::swap(buffer, rhs.buffer);
std::swap(len, rhs.len);
}
char* buffer;
int len;
};