【问题标题】:C++ Print DestructorC++ 打印析构函数
【发布时间】:2020-08-16 10:10:36
【问题描述】:

我是第一次使用指针,我的代码运行正常,但我需要从另一个 .cpp 文件中打印析构函数,但不知道该怎么做。

使用这两个函数删除节点后:

bool LList::remove(node* r) {
    if (r == NULL || search(r->key) == NULL) {
        return false;
    }
    if (r == head) {
        head = head->next;
    }
    else {
        node* prev = getb4(r);
        prev->next = r->next;
    }
    r->next = NULL;
    return true;
}
bool LList::drop(int k) {
    node* currentNode = search(k);
    if (currentNode == NULL || !remove(currentNode))
        return false;
    node* tmp = currentNode;
    while (tmp != NULL) {
        currentNode = currentNode->dup;
        remove(tmp);
        tmp = currentNode;
    }
    return true;
}

...它使用 main.cpp 中的此函数正确打印“(key) removed”。

void testDrop(LList& L) {
    int key;
    cout << "Enter key:  ";
    cin >> key;
    if (L.drop(key))
        cout << key << " removed\n";
    else
        cout << key << " not found in list\n";
}

但是,我还需要它从我的 node.cpp 中打印析构函数而不改变我的 main.cpp。这是析构函数:

node::~node() {
    if (next) delete next;
    if (dup) delete dup;
    cout << "NODE DESTRUCT: key=" << key << " data=" << data << endl;
}

任何建议将不胜感激,谢谢。

【问题讨论】:

  • 也许你想delete r;
  • 使用 std::shared_ptr 它会为你调用析构函数,现代 c++ 代码不应该使用原始指针
  • @Julianne Wright 这个名字 getb4 是什么意思?
  • @VladfromMoscow 它是对我代码中另一个函数的引用。
  • 我需要在删除节点时打印析构函数 -- 如果您的代码没有发出delete 调用,则析构函数无法神奇地找出你“删除了一个节点”。

标签: c++ pointers binary-search-tree destructor


【解决方案1】:

我假设通过打印您的意思是执行析构函数。在这种情况下,每当您对对象调用 delete 时,编译器都会进行检查以确保 析构函数存在于对象中,然后执行它。因此,在这种情况下,您将调用delete n;,其中 n 是您的节点。此外,当您调用 remove node 方法时,您也可以在该节点上调用 delete,只要您确定您的链表和节点析构函数正在适当地处理指针,以免破坏列表的顺序,或导致任何其他更严重的问题,例如内存泄漏或悬空指针。

【讨论】:

  • 非常感谢!这解决了它。
  • 正如我所说,使用 std::shared_ptr,你永远不需要使用原始指针
  • 有时需要使用原始指针,特别是如果您正在学习需要使用它们的数据结构的 CS 课程。
  • 不是智能指针链表的忠实拥护者。如果列表很长,递归销毁可能会很麻烦。
猜你喜欢
  • 2016-12-28
  • 2019-05-14
  • 1970-01-01
  • 1970-01-01
  • 2018-05-02
  • 1970-01-01
  • 2012-07-28
  • 1970-01-01
  • 2014-05-27
相关资源
最近更新 更多