I have a class the members of which are allocated on heap
// client.h
#include <QString>
#include <QTcpSocket>
#include <QTextEdit>
#include <QLineEdit>
#include <QWidget>
class Client : public QWidget
{
Q_OBJECT
public:
Client(const QString &computerName, int portNumber,
QWidget *parent = nullptr);
~Client() = default;
// ...
private:
QTcpSocket *_tcpSocket = new QTcpSocket(this);
QTextEdit *_textInfo = new QTextEdit;
QLineEdit *_textInput = new QLineEdit;
quint16 _nextBlockSize = 0;
};
// client.cpp
Client::Client(const QString &computerName, int portNumber, QWidget *parent)
: QWidget(parent)
{
// ...
}
I never seen default initialization done this way - whether it was done in the ctor or at the best case in the initialization section of it (e.g. _tcpSocket(new QTcpSocket(this))). I can think of multiple reasons against it:
- because we invoke the ctors of the objects we allocate using
new, we can't use forward declaration now - seeing these allocations in the class definition might suggest the user that the class has a non-trivial dtor and the objects must be freed when in fact they don't, because Qt will manage them itself
- seeing
thisin_tcpSocket = new QTcpSocket(this)is just strange to me
So what's the best way to default assign objects on heap?