gpt4 book ai didi

c++ - 在 wxWidgets 中处理链表的正确方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 14:26:12 27 4
gpt4 key购买 nike

我使用 wxWidgets 编写了一个应用程序,它使用 wxList .我在收集列表数据的析构函数中有一些随机错误(段错误)。我找不到从列表中删除项目的明确方法(Erase() VS DeleteNode())。即使迭代项目也有两种风格(list->GetFirst() VS list->begin())。

下面是一个测试类,展示了我在我的应用程序中使用的方法。测试运行完美,没有崩溃。似乎有些指针在释放后正在使用,但我无法通过查看代码来判断。我想我在 Erase() 和 DeleteContents() 调用方面做错了什么。

P.S:在应用程序中,列表包含大约 15,000 个项目,而在测试中只有 9 个。

#include <wx/list.h>
#include <wx/log.h>

class TestItem
{
public:
TestItem(int _x, int _y) { x = _x; y = _y; }
int x;
int y;
};

WX_DECLARE_LIST(TestItem, TestList);

#include <wx/listimpl.cpp>
WX_DEFINE_LIST(TestList);

class Test {

public:
TestList *list;
Test() {
list = new TestList;
}

~Test() {
Clean();
delete list;
}


void CreateAndAddToList(int x, int y) {
TestItem *item = new TestItem(x, y);
list->Append(item);
}

void PrintAll() {
wxLogMessage(wxT("List size: %d"), list->GetCount());
wxTestListNode *node = list->GetFirst();
while (node) {
TestItem *item = node->GetData();
wxLogMessage(wxT("Item: %d, %d"), item->x, item->y);
node = node->GetNext();
}
}

void DeleteAllX(int x) {
wxTestListNode *node = list->GetFirst();
while (node) {
TestItem *item = node->GetData();
if (item->x != x) {
node = node->GetNext();
continue;
}
wxTestListNode *toDelete = node;
node = node->GetNext();
wxLogMessage(wxT("Deleting item: %d, %d"), item->x, item->y);
list->Erase(toDelete);
delete item;
}
}

void Clean() {
list->DeleteContents(true);
list->Clear();
}

static void DoAllTests() {
Test *t = new Test;
t->CreateAndAddToList(1, 1);
t->CreateAndAddToList(1, 2);
t->CreateAndAddToList(1, 3);
t->CreateAndAddToList(2, 1);
t->CreateAndAddToList(2, 2);
t->CreateAndAddToList(2, 3);
t->CreateAndAddToList(3, 1);
t->CreateAndAddToList(3, 2);
t->CreateAndAddToList(3, 3);
t->PrintAll();
t->DeleteAllX(2);
t->PrintAll();
t->Clean();
t->PrintAll();
delete t;
}
};

最佳答案

关于wxList API中list->GetFirst()list->begin()的区别,好像是list->GetFirst () 如果 list 为空则返回 NULL 并且 list->begin() 返回迭代器的值以结束 list->end() 像往常一样用于其他迭代器。 list->GetFirst() 是旧 API,list->begin() 是新 API。主要好处是允许您使用模板,期望迭代器带有 wxList。

wxList 被认为已弃用并被 std::list 取代,但这不应该让你太担心,因为它是在新版本的 wx 内部完成的(wxList 只是成为 wxList 的一个薄包装)。

无论如何,您使用它的方式似乎都很好,而且我在 DeleteAllX() 中没有看到明显的错误,即使它可以稍微简化。

我怀疑是之前的一些内存分配失败了(如果是通过 malloc 完成的,可能会非常安静)并在稍后删除时在列表中造成严重破坏,或者段错误发生在你的析构函数中调用 delete 时拥有对象。由于许多编程错误都可能导致这种情况,在我看来它比 wxList 中的某些问题更有可能,包括分配问题。然而,这很容易检查,只需跟踪对析构函数的调用,您很快就会知道段错误是否来自那里。

关于c++ - 在 wxWidgets 中处理链表的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3842938/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com