2012-10-07 61 views
0

我運行以下代碼時出現「段錯誤11」錯誤。該代碼實際上編譯,但我在運行時得到錯誤。MacOS中的分段錯誤11 X- C++

// ** ** Terror.h

#include <iostream> 
#include <string> 
#include <map> 

using std::map; 
using std::pair; 
using std::string; 

template<typename Tsize> 
class Terror 
{ 
    public: 
    //Inserts a message in the map. 
    static Tsize insertMessage(const string& message) 
    { 
     mErrorMessages.insert(pair<Tsize, string>(mErrorMessages.size()+1, message)); 
     return mErrorMessages.size(); 
    } 

    private: 
    static map<Tsize, string>  mErrorMessages; 
}; 

template<typename Tsize> 
map<Tsize,string> Terror<Tsize>::mErrorMessages; 

// ** ** error.h

#include <iostream> 
#include "Terror.h" 

typedef unsigned short errorType; 
typedef Terror<errorType> error; 
errorType memoryAllocationError=error::insertMessage("ERROR: out of memory."); 

// ** **的main.cpp

#include <iostream> 
#include "error.h" 
using namespace std; 

int main() 
{ 
    try 
    { 
     throw error(memoryAllocationError); 
    } 
    catch(error& err) 
    { 
    } 
} 

我有一種調試代碼,並且當消息被插入到靜態地圖成員中時發生錯誤。一個觀察是,如果我把行:

errorType memoryAllocationError=error::insertMessage("ERROR: out of memory."); 

裏面的「main()」函數,而不是在全局範圍內,那麼一切工作正常。但是我想在全球範圍擴展錯誤信息,而不是在本地範圍。該映射被定義爲靜態的,以便所有「錯誤」實例共享相同的錯誤代碼和消息。你知道我怎麼能得到這個或類似的東西。

非常感謝。

+0

您發佈的代碼不能編譯。請修復它。 –

+0

對不起,我還沒有看到你的評論,現在已經更正。問題是「;」之後定義了Terror <>類。謝謝。 –

+0

它仍然不編譯,因爲沒有'Terror'的構造函數需要'Tsize'作爲參數。 –

回答

0

您需要確保mErrorMessages的構造函數在使用前通過調用insertMessage運行。你可以以任何你想要的方式做到這一點,但你必須做到這一點。

+0

非常感謝。我遵循了你的回答,但是我無法找到以這種方式調用「mErrorMessages」構造函數的方式,以便我可以在全局範圍內填充它。你知道你可以提供給我的一種方式,或者這是不可能的,我應該嘗試另一種方法嗎? –

+0

一種方法是給這個類一個指向地圖的指針,並調用'insertMessage',檢查指針是否爲NULL,如果是,則構造地圖。另一種方法是將兩個對象放在同一個文件中 - 全局範圍內的對象位於同一個文件中,它們按它們在文件中出現的順序構造。 –

+0

非常感謝大衛。根據你的回答和這兩天的搜尋,我得到了我想要的。萬一別人讀取此,我解決我的問題的方式是實行恐怖<>模板類內下列類: –

2

當我試圖在Mac OS X 10.7上運行一個爲OS X 10.8編譯的應用程序時,我遇到了同樣的問題。

將目標設置爲10.7解決了問題。該應用程序在10.7和10.8 OS X環境中運行良好。