vendredi 11 mars 2016

C++ lazy singleton hangs on loading

I have lazy singleton class, that needs to be serialized on the first call.

Header file:

class Singleton
{
public:

    static Singleton& Instance()
    {
        static Singleton theSingleInstance;
        return theSingleInstance;
    }

    void load();
private:
    Singleton();
    Singleton(const Singleton& root);
    Singleton& operator=(const Singleton&);
    std::map<std::string,std::string > m_desc;

    friend class boost::serialization::access;
    template<typename Archive>
    void serialize(Archive& arc, const unsigned int version)
    {
        arc & BOOST_SERIALIZATION_NVP(m_desc);
    }
    const char* FILENAME = "./config.xml";
};

Source file

#include "singleton.h"
Singleton::Singleton()
{
    load();
}


void Singleton::load()
{
    try
    {
        std::ifstream f(FILENAME);
        boost::archive::xml_iarchive arc(f);
        arc & boost::serialization::make_nvp("Config",Instance());
    }
    catch(...)
    {
        std::cout << "Exception" << std::endl;
    }
}

So when I try to start my code using this singleton, it hangs. With the debugger I can see that it does not go to load() method many times (and it's ok). When I pause the debugger, it stops on the line return theSingleInstance;, but it does not go through the breakpoint on this line many times also. What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire