0

I wrote a singleton class who return a smart pointer and i choose to use shared_ptr.

In main i have this error :

undefined reference to `Singleton_Share_ptr::instance

This is my code :

class Singleton_Share_ptr
{
private :
        Singleton_Share_ptr(){value =0;}
        static std::shared_ptr<Singleton_Share_ptr> instance;
        int value;

public :
        Singleton_Share_ptr(const Singleton_Share_ptr&) = delete;
        Singleton_Share_ptr & operator=(const Singleton_Share_ptr&) = delete;
        ~Singleton_Share_ptr() = default;
        int getValue(){ return value;}
        static std::shared_ptr<Singleton_Share_ptr> getInstance()
        {
            if(!instance)
            {
                instance = std:: shared_ptr<Singleton_Share_ptr>(new Singleton_Share_ptr());
            }
            return instance;
        }
};

int main()
{
    std::shared_ptr<Singleton_Share_ptr> s1(Singleton_Share_ptr::getInstance());
    std::cout<<s1->getValue()<<std::endl;
    return 0;
}

Or have anyone any ideea what to write in my main ?

Ac1234
  • 67
  • 6
  • 1
    the singleton instance is static why put it in a shared pointer? – 463035818_is_not_an_ai Sep 23 '20 at 18:21
  • 1
    You shouldn't need a `std::shared_ptr`, the instance will be guaranteed to exist until the program exits anyways. I'd rather recommend using [this _Singleton_ pattern](https://stackoverflow.com/questions/1008019/c-singleton-design-pattern). – πάντα ῥεῖ Sep 23 '20 at 18:22
  • @idclev463035818 The _"anti"_ in _Singleton Pattern_ comes from [cargo culture mysticism](https://stackoverflow.com/questions/64017043/how-to-make-const-variables-filled-at-runtime-accessible-across-all-of-the-progr/64017718#comment113218044_64017718). – πάντα ῥεῖ Sep 23 '20 at 19:27
  • 1
    @πάνταῥεῖ I am completely on your side. I remember what I actually wanted to say with that comment, but it wasnt relevant. My bad for really poor phrasing. Using a hammer for a screw doens't make an "anti hammer" ;) – 463035818_is_not_an_ai Sep 23 '20 at 19:55
  • 1
    @idclev463035818 Not to mention that all of my duct tape constructions always were the longest lasting artefacts I ever made ;) – πάντα ῥεῖ Sep 23 '20 at 20:08

0 Answers0