2011-09-08 95 views
0

我有一個單例(我知道這是一個不好的模式)。爲了控制清潔過程,我使用了一個共享指針。相關的代碼是:當應用程序正在完成時未處理的異常

#ifndef _GLOBAL_LOG_H_ 
#define _GLOBAL_LOG_H_ 

    namespace glog{ 

     class CGlobalLog; 
     typedef boost::shared_ptr<CGlobalLog> globalLogPtr; 

     class CGlobalLog 
     { 
     private: 

      static globalLogPtr m_instance; 
      LogLevel minimiumLogLevel; 
      CGlobalLog(void); 

      static void deleter(CGlobalLog *ptr){ 
       try{ 
        delete ptr; 
       } 
       catch(std:: e) 
       { 
        std::cout << e.what() << "\n"; 
       } 
      } 
      static void create() { m_instance.reset(new CGlobalLog, &CGlobalLog::deleter); } 
      void addMessage_(const std::string& appender, LogLevel level /*= LOGLEVEL_INFO*/,const char* msg, va_list args); 
      ~CGlobalLog(void); 
     public:   
      static globalLogPtr& getInstance(); 
      void addMessage(const std::string& message, std::string appender, LogLevel level = LOGLEVEL_INFO); 

     }; 
     globalLogPtr CGlobalLog::m_instance; 
    }; 

#endif // _GLOBAL_LOG_H_ 

程序工作正常,但是當節目結束,未處理的異常在這一點上拋出:

static void deleter(CGlobalLog *ptr){ 
    try{ 
     delete ptr; //<-- Unhandled exception 
    } 
    catch(std:: e) 
    { 
     std::cout << e.what() << "\n"; 
    } 
} 

漁獲不捕獲異常,所以我不要」不知道如何處理我的錯誤。錯誤被拋出的確切代碼是一個boost庫文件checked_delete.hpp,在這裏:

// verify that types are complete for increased safety 

template<class T> inline void checked_delete(T * x) 
{ 
    // intentionally complex - simplification causes regressions 
    typedef char type_must_be_complete[ sizeof(T)? 1: -1 ]; 
    (void) sizeof(type_must_be_complete); 
    delete x; 
} 

我該如何找到這個錯誤?一些想法?

謝謝!

+2

爲什麼你有一個自定義刪除? –

+2

這條線是什麼意思? catch(std :: e)' –

+1

以及爲什麼你從getInstance返回_reference_到std :: shared_ptr? –

回答

1

我通常不希望在單例中看到共享指針。只要返回一個對你的單例的引用,並且從不保留對它的引用就是一個好習慣。

struct Foo { 
    static Foo &instance() { 
    static Foo foo; 
    return foo; 
    } 
}; 

struct Bar { 
    void someMethod() { 
    Foo &foo = Foo::instance(); // just grab a reference every time you need it 
    // ... 
    } 
}; 

如果您希望保留共享指針並需要以手動方式清理資源,請創建拆卸方法。 boost::shared_ptr將最終清理內存。

就我個人而言,我認爲在外部使用共享指針是次等的。我寫了一些代碼來展示拆除,並且在不知道你爲什麼需要它的情況下似乎並不普遍適用。

如果你想顯式刪除,然後寫一個。

struct Foo { 
    static Foo *foo = 0; 
    static Foo &instance() { 
    if (!foo) 
     throw std::logic_error("Already deleted"); 
    return *foo; 
    } 
    static void Init() { 
    if (foo) 
     throw std::logic_error("Already created"); 
    foo = new Foo; 
    } 
    static void Destroy() { 
    if (!foo) 
     throw std::logic_error("Already deleted"); 
    delete foo; 
    foo = 0; 
    } 
}; 

在記錄的情況下,邏輯錯誤應該是多餘的。如果在您要求時記錄無效,那麼您的應用程序不太可能處於有效狀態。

+1

**如果您必須使用'reset()'方法刪除** boost :: shared_ptr':http://stackoverflow.com/questions/621233/how-to-intentionally-delete-a-boostshared-ptr – karlphillip

+0

如前所述,shared_pointer是強制破壞調用的一種技巧。 – Killrazor

+0

@Killrazor你不能爲此使用'boost :: shared_ptr'。共享指針的每個副本都擁有內存,這就是整個點。如果你想強制銷燬,那麼你必須自己管理記憶。 –

相關問題