Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 736
myWallJSON Avatar asked Dec 17 '25 07:12

myWallJSON


1 Answers

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.

like image 100
sellibitze Avatar answered Dec 19 '25 22:12

sellibitze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!