Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Implementation Singleton problem
Qt 6.11 is out! See what's new in the release blog

Implementation Singleton problem

Scheduled Pinned Locked Moved Unsolved General and Desktop
2 Posts 2 Posters 391 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C Offline
    C Offline
    Creatorczyk
    wrote on last edited by Chris Kawa
    #1

    Hi,
    I wrote class SMessenger which is a singleton but during compilation i get error:
    undefined reference to 'SMessenger::instance_'

    This is my code

    class SMessenger : public QMqttClient
    {
        Q_OBJECT
    public:
        static SMessenger* instance(){
            if(!instance_) instance_ = new SMessenger();
            assert(instance_ != NULL);
            return instance_;
        }
    public slots:
        void sendMsgToDevice(QString topic, bool state);
    
    protected:
        SMessenger(QObject *parent = nullptr);
    private:
        SMessenger(SMessenger const&);
        SMessenger& operator=(SMessenger const&);
    
        static SMessenger* instance_;
        QMqttClient *m_mqttClient;
    
    private slots:
        void slotErrorChanged(const QMqttClient::ClientError e);
        void slotStateChanged();
        void slotDisconnected();
        void slotConnected();
    
    signals:
        void signalNewParamsFromGreenhouse(Current_parameters parameters);
    };
    

    The problem is in the method instance()

    1 Reply Last reply
    0
    • Chris KawaC Offline
      Chris KawaC Offline
      Chris Kawa
      Lifetime Qt Champion
      wrote on last edited by
      #2

      You're missing a definition of your static variable. Put that in your .cpp file:

      SMessenger* SMessenger::instance_ = nullptr;
      

      Btw. don't forget to delete your singleton before your application object is destroyed. No QObject should live longer than that. One way to do it is to connect QApplication::aboutToQuit signal to your singleton's deleteLater slot when you're creating it.

      Btw.2 Don't use NULL. It's an old C style macro. If you need to be that explicit use nullptr or you could just assert(instance_).

      1 Reply Last reply
      5

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved