我有以下 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/