在创建更高阶的地图函数时,我应该使用指针或引用还是值?

时间:2013-12-14 10:16:52

标签: 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);

    };

现在我遇到了问题。我真的想把地图函数写成:

  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);
    };

因为前面的地图无论如何都需要被破坏,并且不会导致内存泄漏。传统上地图取代了一个值。但是,我还必须使event_node成为一个值,这将导致它被复制到任何地方。我是一个初学者,所以我会陷入我应该采取的方法。

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

完整代码:

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

1 个答案:

答案 0 :(得分:2)

您可以使用shared_ptr<LoggerEvent>之类的智能指针将其存储在容器中并传递它。一旦智能指针的所有副本都被销毁,智能指针指向的对象将被销毁。

相关问题