Implementation Singleton problem
Unsolved
General and Desktop
-
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()
-
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'sdeleteLater
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 usenullptr
or you could justassert(instance_)
.