[英]Conversion constructor
Can any one tell me how the char* member gets deleted after conversion constructor is called. 谁能告诉我在调用构造函数后如何删除char *成员。
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. 您最终得到两个
String
对象(其中一个是临时对象),该对象持有指向相同地址的指针。 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
. 注意 :正如@kolrabi指出的那样,您应该在分配给
strdup
的指针上调用free
,而不是delete
。
Let's analyze s = "abc"
: 让我们分析
s = "abc"
:
First of all, this is an assignment, not an instantiation, because s
has already been declared. 首先,这是一个赋值,而不是实例化,因为已经声明了
s
。
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
. 因此,为此的编译解决方案是创建一个以
"abc"
作为String
构造函数参数的临时String
对象,然后调用String
赋值运算符以将该临时对象复制到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
. 现在,由于尚未实现此类的赋值运算符,因此将调用默认赋值运算符,并将每个成员变量从临时
String
对象复制到s
。
Finally, the temporary String
object is destroyed and the memory pointed by its m
variable is deallocated. 最后,临时
String
对象被销毁,并且由其m
变量指向的内存被释放。 As a result, you end up with sm
pointing to an invalid piece of memory. 结果,您最终得到
sm
指向无效的内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.