简体   繁体   中英

Conversion constructor

Can any one tell me how the char* member gets deleted after conversion constructor is called.

The output is Debug Assertion Failed

class String
{
public:
    char* m;
    String()
    {
        m = NULL;
    }
    String(const char* str)
    {
        m = strdup(str);
    }
    String(const String& I)
    {
        m = strdup(I.m);
    }
    ~String()
    {
        delete m;
    }
};


void main()
{
    String s;
    s = "abc";
    s = "bcd";
}

The problem is that you have not implemented an assignment operator. So when you do this

s = "abc";

you end up with two String objects (one of them a temporary) holding a pointer to the same address. They both try to delete the same object. You need to follow the rule of three .

Note : as @kolrabi has pointed out, you should be calling free on a pointer allocated with strdup , not delete .

Let's analyze s = "abc" :

First of all, this is an assignment, not an instantiation, because s has already been declared.

So the compilation solution for this would be to create a temporary String object with "abc" as the argument to the String constructor, and then call the String assignment operator in order to copy that temporary object into s .

Now, since you have not implemented an assignment operator for this class, the default assignment operator is called, and simply copies each one of the member variables from the temporary String object into s .

Finally, the temporary String object is destroyed and the memory pointed by its m variable is deallocated. As a result, you end up with sm pointing to an invalid piece of memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM