c++ - 创建高阶映射函数时,我应该使用指针、引用还是值?

标签 c++ pointers

我有以下 C++ 代码:

  EventQueue * EventQueueNode::map(std::function<LoggerEvent *(LoggerEvent *)> func, 
                                   bool stop_propagate = true){
            auto old_node = this->event_node;
            this->event_node = func(this->event_node);
            delete old_node;
            return this->right()->map(func, stop_propagate);
    };

如果用户返回相同的指针,这段代码就会中断,但如果我不删除它,它就会泄漏内存。

EventQueue 是一个循环双向链表。它有一个头部,它固定两端,但充当端点:

    EventQueue * EventQueue::map(std::function<LoggerEvent *(LoggerEvent *)> func, 
                                 bool stop_propagate = false) {
            if(stop_propagate)
                    return this;

            return this->right()->map(func, true);

    };

现在我有一个问题。我真的很想将 map 函数写成:

  EventQueue * EventQueueNode::map(std::function<LoggerEvent(LoggerEvent)> func, 
                                   bool stop_propagate = true){

            this->event_node = func(this->event_node);
            return this->right()->map(func, stop_propagate);
    };

因为之前的map无论如何都要销毁,不会造成内存泄漏。传统上, map 会替换值。但是我还必须使 event_node 成为一个值,这将导致它被复制到任何地方。我是一个初学者,所以我被困在我应该采取的方法上。

解决这个问题的好方法是什么?

完整代码:

http://pastebin.com/NT1pD5ar (大部分代码处于构建状态,我有更多问题)

最佳答案

您可以使用像 shared_ptr<LoggerEvent> 这样的智能指针将其存储在容器中并传递。智能指针的所有拷贝销毁后,智能指针指向的对象将被销毁。

关于c++ - 创建高阶映射函数时,我应该使用指针、引用还是值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20582032/

相关文章:

c - 数组指针的自动类型转换

c++ - 如何使用 clang 从源文件中提取标题?

c - 指针程序

c - 如何将两个变量的地址存储在后续C程序的指针中

c++ - .cpp 文件中的两个 namespace 用于比较

c++ - 一个类应该使用函数指针调用另一个类的方法

c - 用指针在c中打乱链表

c++ - 我可以为迭代器赋值吗?

c# - 项目引用另一个项目的 obj 文件夹中的 dll - 有时编译有时不编译

c++ - 如何识别类类型以将shared_ptr强制转换为该类型