0

I am trying to write proper c++ code, and EASY to read

i have a class for UDP traffic

untill now i have declared it as global obj and added extern to all files,

after some reading i have understoom the wat to go is Singleton class and gets pointer to it every time i want to use that class

i am tring some thing like that but i cant understand how to make it work

this is in the traficMngr.h:

class traficMngr {
public:
    traficMngr();
    virtual ~traficMngr();

    static traficMngr *instance()
        {
            if (!s_instance)
              s_instance = new traficMngr;
            return s_instance;
        }
private:
    static traficMngr* s_instance;

and now every where in the code i should just do :

traficMngr* tfcMngr=traficMngr::instance();

and to use lets say send msg just do

tfcMngr->sendMsg(Buff,Size);

Is this the right way to use it? will it work at all?

JohnnyF
  • 1,053
  • 4
  • 16
  • 31
  • 2
    Some would argue that for singletons there is *no* right way to implement and use them. In their eyes a singleton is no better than a global variable, and global variables should be avoided at all costs. – Some programmer dude Jun 16 '17 at 07:42
  • As for your question, a big part of the singleton pattern is that no one else should be able to construct or destruct instances of the singleton class (because that makes it not a singleton any more). Your class allows it. – Some programmer dude Jun 16 '17 at 07:44
  • @edgarrokyan I disagree wioth you marking this as a duplicate of the question you linked to. That question (over there) is about implementation details of the singleton pattern, whereas this one is about the relevance of the singleton pattern in modern c++ techniques. – Michaël Roy Jun 16 '17 at 08:09
  • 1
    The current trend is to run away from the singleton pattern, as fast as possible – Michaël Roy Jun 16 '17 at 08:10

0 Answers0