2

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?

myWallJSON
  • 9,110
  • 22
  • 78
  • 149
  • possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix), specifically last item of http://stackoverflow.com/a/12574407/635608 – Mat Nov 17 '12 at 14:19

3 Answers3

14

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.

sellibitze
  • 27,611
  • 3
  • 75
  • 95
  • This is a neat answer, especially the hint to thread-safetyness. What displeasures me is, that the presented singleton is copyable, isn't it? Is it possible to have both: a shared_ptr-singleton which is noncopyable? – AquilaRapax Jun 26 '13 at 15:24
  • @AquilaRapax: good point! Yes, i think this should be easily possible. I'd simply make the copy ctor private or turn it into a deleted function. – sellibitze Aug 09 '13 at 08:49
2

You should define

boost::shared_ptr<connector> connector::instance;

in your *.cpp This makes linker allocate the memory for this static member in static data area.

Jurlie
  • 1,014
  • 10
  • 27
1

You have to define static members outside of the class declaration. Here's what the definition looks like:

boost::shared_ptr<connector> connector::instance;

It should be in a cpp, for you probably transmitter.cpp

David
  • 27,652
  • 18
  • 89
  • 138