QNetworkAccessManager singleton class example
Unsolved
General and Desktop
-
@hiren21
actually any singleton example on the web is applicable since the pattern is independant of the type, but here you go:QNetworkAccessManager* getNAM() { static QNetworkAccessManager* nam = new QNetworkAccessManager; return nam; }
-
.h file
class QNAMwrapper{ static QNetworkAccessManager* m_qnam; public: static QNetworkAccessManager* getQNAM() { Q_ASSERT_X(m_qnam,"QNAMwrapper","You must create an instance of QNAMwrapper before using the QNAM"); return m_qnam; } QNAMwrapper(){ Q_ASSERT_X(!m_qnam,"QNAMwrapper","Only one instance of QNAMwrapper can be created"); if(!m_qnam) m_qnam=new QNetworkAccessManager; } ~QNAMwrapper(){delete m_qnam; m_qnam=Q_NULLPTR;} };
cpp file
QNetworkAccessManager* QNAMwrapper::m_qnam = Q_NULLPTR;
This works like QApplication and handles the lifecycle of QNetworkAccessManager. So in your main add
QNAMwrapper qnamw;
and then you can use the QNetworkAccessManager viaQNAMwrapper::getQNAM();