2013-12-14 14 views
1

我在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(大部分代碼是在施工狀態,並有更多的問題,我有)

回答

2

您可以使用智能指針像shared_ptr<LoggerEvent>將其存放在容器中,並通過它。一旦智能指針的所有副本被銷燬,智能指針指向的對象將被銷燬。

+0

這聽起來很有趣,每次我看它時,C++似乎都會演變成更好的語言。從什麼時候在C++中? –

+0

好吧,助推器已經有了它們很久了。他們在幾年前被納入標準(至少他們應該)。 – pvgoran

+1

新標準中還有更多有趣的東西,比如「auto」變量(儘管這些變量很容易被濫用)和「for each」循環支持。 – pvgoran

相關問題