Noah Roth
Noah Roth

Reputation: 9220

Custom string class and destructors?

I was bored today and I want to create my own little string class. I really like the 'System.String' class in .Net for it's Split/Replace/Remove etc. functions and I want to attempt to implement them.

My problem however is the destructor. If I have multiple instances of my string class that hold the same string, will all of them try and delete[] the same memory when the destructor is called??

For example:

void DoSomething() {
    MyStringClass text = "Hello!";
    {
        MyStringClass text2 = text;
        // Do something with text2
    } // text2 is destroyed, but so is the char* string in memory
    // text now points to useless memory??
}

Am I understanding this right? Lol.

Thanks,

Alex

EDIT:

Oops, I forgot to include the code:

class string {
    unsigned int length;
    char* text;

public:

    string() : length(0), text(NULL) { }

    string(const char* str) {
        if (!str) throw;
        length = strlen(str);
        text = new char[length];
        memcpy(text, str, length);
    }

    ~string() {
        delete[] text;
    }
};

Upvotes: 0

Views: 1317

Answers (1)

JohnMcG
JohnMcG

Reputation: 8815

You are correct -- both will attempt to delete [] the same memory block.

You did not define a copy constructor for your class, so you will get the default one, which performs a shallow copy of your pointer.

When text2 falls out of scope, the pointer will be delete []d. When text1 falls out of scope, the same pointer will be delete []d again, resulting in undefined behavior.

There are a number of ways to get around this, the simplest being to define your copy constructor and assignment operator.

Upvotes: 1

Related Questions