我在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 会替换值。但是然后我还必须将event_node设为一个值,这将导致它被复制到任何地方。我是一个初学者,所以我陷入了应该采取的方法。
解决这个问题的好方法是什么?
完整代码:
http://pastebin.com/NT1pD5ar(大多数代码处于构造状态,我还有更多问题)
最佳答案
您可以使用诸如shared_ptr<LoggerEvent>
之类的智能指针将其存储在容器中并传递给周围。一旦销毁所有智能指针副本,该智能指针指向的对象将被销毁。