C ++ User Defined Conversion - Implicit Conversion

I have a question about user defined transform.

class String {
    char* m_data;

public:
    String(): m_data(NULL) {}
    String(const char* cstr): m_data(new char[strlen(cstr)+1]) {
        strcpy(m_data, cstr);
    }
    ~String() {
        delete[] m_data;
    }
    String& operator=(const char* cstr) {
        delete[] m_data;
        m_data = new char[strlen(cstr)+1];
        strcpy(m_data, cstr);
        return *this;
    }
    operator const char*() const { 
        return m_data;
    }
};

      

While this works:

int main(int argc, char** argv) {
    String a;
    String b;
    a = "aaa";
    b = (const char *)a;
    return 0;
}

      

It does not mean:

int main(int argc, char** argv) {
    String a;
    String b;
    a = "aaa";
    b = a;
    return 0;
}

      

I am getting a double free or corruption

runtime error. Valgrind talks about an incorrect deletion.

Why should I specify it explicitly? I thought this would work with explicit operator const char*()

. Am I doing something wrong?

+3


source to share


1 answer


You forgot to define the copy destination operator :

String& operator=(const String& other) {
    if(this != &other) {
        char* new_data = new char[strlen(other.m_data)+1];
        strcpy(new_data, other.m_data);
        delete[] m_data;
        m_data = new_data;
    }
    return *this;
}

      

Because of this, your compiler had to define a default "default" assignment operator, which simply assigns all fields "other" to the current object:



String& operator=(const String& other) {
    m_data = other.m_data;
    return *this;
}

      

So, you have two pointers to the same m_data

in a

and b

, and on exit main

, delete[]

will be called twice.

+7


source







All Articles