Search code examples
c++design-patternssingletonshared-ptr

C++ shared_ptr based singletone what causes link error?


So I try this code:

#ifndef TRANSMITTER_H
#define TRANSMITTER_H
class connector
{   
public:
    static boost::shared_ptr<connector> Instance(){
        if(!instance)
        {
            instance = boost::shared_ptr<connector>(new connector());
        }
        return instance;
    }
private:
    connector(){}
    static boost::shared_ptr<connector> instance;
};
#endif //TRANSMITTER_H

But get link error:

Error   3   error LNK2001: unresolved external symbol "private: static class boost::shared_ptr<class connector> connector::instance" (?instance@connector@@0V?$shared_ptr@Vconnector@@@boost@@A)

What is wrong with shared_ptr I want to return? Shall I make it function scope static variable?


Solution

  • This

    static boost::shared_ptr<connector> instance;
    

    inside your class definition is just a declaration. What you don't seem to have is a definition of it. This definition has be outside of the class definition.

    However, you should probably prefer to do this:

    class connector
    {   
    public:
        connector(connector const&) = delete;
        connector& operator=(connector const&) = delete;
    
        static boost::shared_ptr<connector> Instance()
        {
            static boost::shared_ptr<connector> instance (new connector);
            return instance;
        }
    private:
        connector(){}
    };
    

    In this case instance is defined as a static function-local object inside your inline function definition of Instance. The nice thing about it is that this kind of initialization is guaranteed to be thread-safe in C++11.