0
votes

I am trying to write a singleton class and I followed the standard template as below. But I get /usr/include/c++/7/ext/new_allocator.h:136:4: error: is private within this context { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

status_publisher.hpp
    namespace test {
    class StatusPublisher {
     public:
       static std::shared_ptr<StatusPublisher> getStatusPublisher();

     private:
       StatusPublisher();
       static std::shared_ptr<StatusPublisher> instance_;  
    }

status_publisher.cpp

 namespace test {
  std::shared_ptr<StatusPublisher> StatusPublisher::getStatusPublisher() {
     if(instance_.get()==nullptr) {
         instance_ = std::make_shared<StatusPublisher>();
     }
     
     return instance_;
    }

    StatusPublisher::StatusPublisher() {

    // Some code
    }
}

1

1 Answers

0
votes

As instance_ is initially a not a shared_ptr in your code, the .get() would not work there, as the instance_ is not a object like shared_ptr<StatusPublisher> { nullptr }. I suggest you move instance_ declaration into StatusPublisher::getStatusPublisher, and return the instance_ there. As it is declared static, only one instance will be made.

Edit : I've seen another alternative answer that suggests to use raw pointer. However, as the shared_ptr has some pro-con to use the raw pointer, I suggest the shared_ptr version anyway:

status_publisher.hpp

namespace test {
   class StatusPublisher {
 public:
   static std::shared_ptr<StatusPublisher> getStatusPublisher();

 private:
   StatusPublisher();
   };
}

status_publisher.cpp

namespace test {
     std::shared_ptr<StatusPublisher> StatusPublisher::getStatusPublisher() {
         static std::shared_ptr<StatusPublisher> instance_ = std::shared_ptr<StatusPublisher>{new StatusPublisher()};
         return instance_;
     }

    StatusPublisher::StatusPublisher() {

    // Some code
    }
}