Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Call for Presentations - Qt World Summit

    Unsolved Implementation Singleton problem

    General and Desktop
    2
    2
    113
    Loading More Posts
    • 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
      Creatorczyk last edited by Chris Kawa

      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 Reply Quote 0
      • Chris Kawa
        Chris Kawa Moderators last edited by

        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 Reply Quote 5
        • First post
          Last post