Singleton example in C ++ apply to QT

0

Hi, I want to apply this program that is done in c ++ to QT since I do it in another way but it seems not to be the correct one. What I usually do when I use this method, the singleton method, what I do is create a static object but what you have to do is make _instance to the pointer and initialize it the first time it is called. The code in c ++ that I am trying to adapt QT or look for a similar example.

class GlobalClass
{
    int m_value;
  public:
    GlobalClass(int v = 0)
    {
        m_value = v;
    }
    int get_value()
    {
        return m_value;
    }
    void set_value(int v)
    {
        m_value = v;
    }
};

// Default initialization
GlobalClass *global_ptr = 0;

void foo(void)
{
  // Initialization on first use
  if (!global_ptr)
    global_ptr = new GlobalClass;
  global_ptr->set_value(1);
  cout << "foo: global_ptr is " << global_ptr->get_value() << '\n';
}

void bar(void)
{
  if (!global_ptr)
    global_ptr = new GlobalClass;
  global_ptr->set_value(2);
  cout << "bar: global_ptr is " << global_ptr->get_value() << '\n';
}

int main()
{
  if (!global_ptr)
    global_ptr = new GlobalClass;
  cout << "main: global_ptr is " << global_ptr->get_value() << '\n';
  foo();
  bar();
}

Someone who knows about it because I could use a similar example very well.

    
asked by Perl 22.10.2016 в 02:09
source

2 answers

3

A simple example of Singleton is as follows:

//GlobalClass.h

class GlobalClass
{
public:
  static GlobalClass* get()
  {
    if ( m_instance == nullptr )
    {
      m_instance = new GlobalClass;
    }
    return m_instance;
  }
  void set_value( int value )
  {
    m_value = value;
  }

  int get_value()
  {
    return m_value;
  }

  ~GlobalClass()
  {
    delete m_instance;
  }

private:
  GlobalClass() : m_value( 0 )
  {
  }

  static GlobalClass* m_instance;

  int m_value;
};

GlobalClass* GlobalClass::m_instance = nullptr;

To use it simply:

GlobalClass::get()->set_value(2);
auto val = GlobalClass::get()->get_value();
    
answered by 22.10.2016 / 16:41
source
0

Dr. Stroustrup recommends that, the place of a "singleton", use a function that returns a reference to a static local object. He gives this example:

X& myX()
{
    static X my_x {3};
    return my_x;
}

link

Another alternative is a header file that I have written: link . It can be used to guarantee the order of initialisation, although the objects are in different compilation units.

    
answered by 05.11.2016 в 01:36