【发布时间】:2020-09-28 19:20:45
【问题描述】:
我正在尝试正确实现一个尊重 5 规则的简单链表。我得到了大约 3,虽然我在这里已经有我的怀疑,但从那里开始,我如履薄冰。由于这似乎是一个相当普遍的话题,我很惊讶我找不到一个完整的例子。我找到了一些零碎的东西,但没有完整的集合。因此,如果我对此进行了排序,它也可以作为未来的参考。
我添加了一个示例 class Data 来说明一些现实生活中的“复杂性”,因为大多数示例只有一个带有单个 int 的节点和一个指向下一项的指针。
编辑:我已经使用 PaulMcKenzie 如下所示的代码完成了课程,它在 VS2019 中编译正常,但在移动构造函数和赋值运算符上发出警告:C26439: This kind of function may not throw. Declare it 'noexcept' (f.6)。
class Data
{
public:
int id;
string name;
float[5] datapoints;
};
class Node
{
public:
Node(Data d = { 0 }, Node* n = nullptr) : data(d), next(n) {};
Data& GetData() { return data; }
Node*& GetNext() { return next; }
private:
Data data;
Node* next;
};
class NodeList
{
public:
NodeList() :head(nullptr) {} // constructor
~NodeList(); // 1. destructor
NodeList(const NodeList& src); // 2. copy constructor
NodeList& operator=(const NodeList& src); // 3. copy assignment operator
NodeList(NodeList&& src); // 4. move constructor
NodeList& operator=(NodeList&& src); // 5. move assignment operator
void AddToNodeList(Data data); // add node
private:
Node* head;
};
void NodeList::AddToNodeList(Data data)
{
head = new Node(data, head);
}
NodeList::~NodeList()
{
Node* n = head, * np;
while (n != nullptr)
{
np = n->GetNext();
delete n;
n = np;
}
}
NodeList::NodeList(const NodeList & src) : head(nullptr)
{
Node* n = src.head;
while (n != nullptr)
{
AddToNodeList(n->GetData());
n = n->GetNext();
}
}
NodeList& NodeList::operator= (const NodeList& src)
{
if (&src != this)
{
NodeList temp(src);
std::swap(head, temp.head);
}
return *this;
}
NodeList::NodeList(NodeList&& src) : head{src.head}
{
src.head = nullptr;
}
NodeList& NodeList::operator=(NodeList&& src)
{
if (this != &src)
std::swap(src.head, head);
return *this;
}
【问题讨论】:
-
要检查您现在拥有的代码的正确性,您应该有一个小的
main函数来创建、复制和销毁NodeList对象。然后查看是否有任何内存泄漏、故障等。您应该先这样做,然后再编写其他两个缺少的函数。此外,不要为这些函数编写存根。要么完全实施它们,要么不拥有它们。原因是编译器可能会在您的测试过程中调用这些函数,不完整的移动函数可能会导致问题。例如,您当前的移动分配没有返回任何内容,这是错误的。 -
谢谢你们。我已经把它放在一个小程序中并修复了很多错别字。你是对的,另外两个不应该有正确的代码,但我希望稍后用希望有用的 cmets 完成它们。
标签: c++ linked-list copy-constructor assignment-operator move-constructor