【发布时间】:2011-10-07 23:20:07
【问题描述】:
我有课
class Node {
public:
int value;
Node * next;
Node();
Node(const Node& other);
Node& operator= (const Node& other);
};
它不是很有用,但它有一个重写的赋值运算符。里面的所有东西都是public,因为我是一个非常开放和合作的人。
现在我在其他地方有一个这些节点的数组:
Node * nodes = new Node[15];
当我尝试将一个节点分配给我的节点数组时:
nodes[0] = Node();
我遇到了严重的崩溃。
我的赋值运算符如下所示:
Node& Node::operator= (const Node& other) {
// watch out for self assignment
if (this == &other) return *this;
delete this->next;
this->next = new Node(*(other.next)); // call the copy constructor
this->value = other.value;
return *this;
}
我觉得在尝试取消引用其成员之前,我应该检查 this 是否为 NULL。对可能出了什么问题有任何想法吗?
【问题讨论】:
-
*(other.node)不应编译。Node没有成员node。 -
后编辑:
delete this->node也不应该编译。Node没有成员node。也许你还没有发布真正的代码? -
啊哈哈,是的。谢谢。不,这不是真正的代码,这足以表达情况。
-
另外,您的“删除 + 分配新”模式不是异常安全的。
-
@asveikau 为什么“删除+分配新”不是异常安全的?听起来很有趣,我很想知道!