Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Implementation Singleton problem



  • 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()


  • Moderators

    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_).


Log in to reply