【发布时间】:2020-08-02 11:22:54
【问题描述】:
所以我遇到了一个问题,我的代码构建成功,但是一旦我在 Visual Studio 上运行它,它就会停止并显示“系统资源不足,无法完成请求的服务。”。代码基本上是创建一个链表,我正在实现一个 Set 类来创建列表并对其进行基本操作。
我认为这是我的复制构造函数、析构函数和 = 运算符的问题。下面是代码:
main.cpp
#include <iostream>
#include "Set.h"
using namespace std;
int main()
{
Set a;
a.insert("aa");
a.insert("bb");
a.insert("cc");
a.insert("dd");
Set b;
b.insert("ee");
b.insert("ff");
Set c;
Set c(b);
cout << "C is " << endl;
c.dump();
cout << endl;
c = a;
cout << "C is " << endl;
c.dump();
Set.h
class Set
{
public:
Set();
bool empty() const;
int size() const;
bool insert(const ItemType& value);
bool erase(const ItemType& value);
bool contains(const ItemType& value) const;
bool get(int pos, ItemType& value) const;
void swap(Set& other);
void dump();
~Set();
Set(const Set& other);
Set& operator=(Set other);
private:
struct Node
{
ItemType data;
struct Node* next;
struct Node* prev;
}m_dummy;
Node *m_dummyPtr;
int m_size;
};
Set.cpp //仅复制构造函数、析构函数和=operator
Set::~Set()
{
Node* current = m_dummyPtr->next;
Node* next;
for (int i = 0; i < m_size;i++)
{
next = current->next;;
delete current;
current = next;
}
m_dummyPtr->next = nullptr;
m_dummyPtr->prev = nullptr;
}
Set::Set(const Set& other)
{
m_size = other.m_size;
Node* p = other.m_dummyPtr->next;
m_dummyPtr = &m_dummy;
m_dummyPtr->data = {};
m_dummyPtr->next = m_dummyPtr;
m_dummyPtr->prev = m_dummyPtr;
if (m_size == 0)
;
else
{
for (int i = 0;i < m_size;i++)
{
insert(p->data);
p = p->next;
}
}
}
Set& Set::operator=(Set other)
{
if (this != &other) {
swap(other);
}
return *this;
}
设置插入功能实现
bool Set::insert(const ItemType& value)
{
if (m_size == 0)
{
Node* newNode = new Node;
newNode->data = value;
newNode->prev = &m_dummy;
newNode->next = &m_dummy;
m_dummy.next = newNode;
m_dummy.prev = newNode;
m_size++;
return true;
}
else if (contains(value))
{
return false;
}
else
{
Node* newNode1 = new Node;
Node* p = m_dummy.prev;
m_dummy.prev = newNode1;
newNode1->data = value;
newNode1->next = &m_dummy;
newNode1->prev = p;
p->next = newNode1;
m_size++;
return true;
}
}
【问题讨论】:
-
您的错误消息听起来好像您没有剩余的 RAM 来运行您的程序。如果您从
main中删除b.insert("ff");之后的所有内容,您的程序会运行吗? -
是的,如果我把它注释掉,它会起作用
-
可能在某个地方你没有初始化
m_size,这导致你分配了大量的内存。我会在您的调试器中监视该变量,并查看每个集合占用的值。 -
为什么你认为这是你的复制构造函数、析构函数和 =operator 的问题?
-
因为没有这些代码运行良好。我可以执行其他功能
标签: c++ class constructor linked-list destructor