最近踩到一坑,編譯cpp 文件的順序不同導(dǎo)致程序異常偿曙。
假設(shè)一個類A中定義了靜態(tài)成員變量羔巢,在寧一個類B的構(gòu)造中需要用到這個靜態(tài)成員變量。那么如果用 類B 來聲明一個全局對象启摄,就得注意了幽钢。有可能在 類B構(gòu)造過程中,類A 的靜態(tài)成員變量還未初始化導(dǎo)致異常蕾羊。
解決方法, 可以在編譯鏈接的時候保證,類A 的靜態(tài)成員變量初始化的地方出現(xiàn)在類B 的構(gòu)造前面书闸。
logging.hpp
#pragma once
#include <iostream>
#include <functional>
#include <map>
#include <string>
using std::string;
class CLog
{
public:
enum class ELevel{eTrace,eDebug};
typedef std::function<void(ELevel,const string &,const string &)> PFunction;
CLog(ELevel value,const string &szDomain);
void SetFunction(ELevel eLevel,PFunction Function);
private:
typedef std::map<ELevel,PFunction> DestMap;
static DestMap m_DestMap;
ELevel m_eLevel;
string m_szDomain;
};
void InitLog();
class CLogger
{
public:
CLogger()
{
std::cout << "test: CLogger" << std::endl;
InitLog();
}
};
logging.cpp
#include <functional>
#include <iostream>
#include "logging.hpp"
CLog::CLog(ELevel eLevel,const std::string & szDomain)
:m_eLevel(eLevel),m_szDomain(szDomain)
{
std::cout <<" test: CLog" <<std::endl;
}
void CLog::SetFunction(ELevel eLevel, PFunction Function)
{
m_DestMap[eLevel] = Function;
}
void OutputTest(CLog::ELevel eLevel ,const std::string &szDomain,const std::string &szBody)
{
std::cout << "test : OutputTest." << std::endl;
}
void InitLog()
{
CLog Log(CLog::ELevel::eDebug,"test");
Log.SetFunction(CLog::ELevel::eDebug,OutputTest);
}
main.cpp
#include "logging.hpp"
#include <iostream>
//由于 Logger 構(gòu)造過程中用到了 m_DestMap, 但是此時 m_DestMap 并沒有初始化
//導(dǎo)致程序崩潰浆劲, 應(yīng)該寫成CLog::Destmap CLog::m_DestMap;CLogger Logger;
CLogger Logger;
CLog::DestMap CLog::m_DestMap;
int main()
{
std::cout << " test: main"<<std::endl;
return 0;
}