0

I'm trying to make a "thread-safe", singleton, but I'm getting this stupid error:

Class Header:

class Engine
{
public:
    static Engine* Instance(void);
private:
    Engine() {}
    static std::atomic<Engine*> pinstance;
    static std::mutex m_;

Class Source:

std::atomic<Engine*> Engine::pinstace { nullptr };
std::mutex Engine::_m;

Engine* Engine::Instance()
{
    if (pinstance == nullptr) {
    //            ^^ I get error here
        std::lock_guard<std::mutex> lock(m_);
    if (pinstance == nullptr) {
    //            ^^ I get error also here
        pinstance = new Engine();
    }
    }
    return pinstance;
}

Thank you

Malium
  • 79
  • 1
  • 6
  • 1
    If you're using C++ 11, there are much easier ways to create thread-safe singletons. http://stackoverflow.com/questions/8102125/is-local-static-variable-initialization-thread-safe-in-c11 In other words, you're doing all the work that the C++ 11 standard now guarantees must be done for static variables. – PaulMcKenzie Apr 12 '15 at 21:14
  • So you think that using visual studio 2013, and doing: `Engine& Engine::Singleton() { static Engine instance; return instance; }` will work? – Malium Apr 12 '15 at 21:52
  • Yes, that is all you need to do, but not with Visual Studio 2013. See the link here: http://stackoverflow.com/questions/28096970/when-is-a-divide-by-zero-not-a-divide-by-zero-a-puzzle-in-the-debugger-static/28098631#28098631 You need to use Visual Studio 2015, as that version correctly implements the static initialization. – PaulMcKenzie Apr 12 '15 at 23:11

0 Answers0