![](/img/trans.png)
[英]When should I pass a “reference to pointer” or a “pointer to pointer” rather then just a pointer to the function?
[英]When creating a higher order map function should I use a pointer or a reference or a value?
我在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);
};
因為無論如何都需要銷毀先前的映射,並且它不會導致內存泄漏。 傳統上,地圖會替換值。 但是然后我還必須將event_node設為一個值,這將導致它被復制到任何地方。 我是一個初學者,所以我陷入了應該采取的方法。
什么是解決這個問題的好方法?
完整代碼:
http://pastebin.com/NT1pD5ar (大多數代碼處於構造狀態,我還有更多問題)
您可以使用諸如shared_ptr<LoggerEvent>
類的智能指針將其存儲在容器中並傳遞它。 一旦銷毀所有智能指針副本,該智能指針指向的對象將被銷毀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.