Witam, analizuję pewien kod, który tworzy serwer tcp i chciałbym spytać czy nie ma tu ryzyka wycieku pamięci i czy ogólnie jest optymalnie zrobiony, bo działać to działa. W kodzie zaznaczyłem jeszcze miejsca w których nie wszystko jest dla mnie jasne.
Server.h
#ifndef SERVER_H
#define SERVER_H
#include <QTcpServer>
class Socket;
class Server : public QTcpServer
{
public:
Server(QObject *parent = nullptr);
bool startServer(quint16 port);
protected:
void incomingConnection(qintptr handle);
private:
QList<Socket*>mSockets;
};
#endif // SERVER_H
Server.cpp
#include "Server.h"
#include "Socket.h"
#include<QDebug>
#include<QTextStream>
Server::Server(QObject *parent) : QTcpServer(parent)
{
}
bool Server::startServer(quint16 port)
{
return listen(QHostAddress::Any, port);
}
void Server::incomingConnection(qintptr handle)
{
qDebug() << "Client connected with a handle: " << handle;
auto socket = new Socket(handle, this); //1. czy tutaj nie ma ryzyka wycieku pamięci?
mSockets << socket;
for(auto i : mSockets)
{
QTextStream T(i);
T << "Server: Connected" << handle;
i->flush();
}
connect(socket, &Socket::mReadyRead, [&](Socket *S)
{
qDebug() << "mReadyRead";
QTextStream T(S);
auto text = T.readAll();
for(auto i : mSockets)
{
QTextStream K(i);
K << text;
i->flush();
}
});
connect(socket, &Socket::mStateChanged, [&](Socket *S, int ST) //2. tutaj wywołuje się ciało tego connect, gdy emitowany jest sygnał mStateChanged tak?
{ //3. i co to za zapis [&](Socket *S, int ST) ? Bo pierwszy raz z takim się spotykam
qDebug() << "mStateChanged with a handle: " << S->socketDescriptor();
if(ST == QTcpSocket::UnconnectedState)
{
qDebug() << "Unconnected state with a handle: " << S->socketDescriptor();
mSockets.removeOne(S);
for(auto i : mSockets)
{
QTextStream K(i);
K << "Server: Client " << S->socketDescriptor() << " disconnected";
i->flush();
}
}
});
}
Socket.h
#ifndef SOCKET_H
#define SOCKET_H
#include <QTcpSocket>
class Socket : public QTcpSocket
{
Q_OBJECT
public:
Socket(qintptr handle, QObject *parent = nullptr);
signals:
void mReadyRead(Socket*);
void mStateChanged(Socket*, int);
};
#endif // SOCKET_H
Socket.cpp
#include "Socket.h"
Socket::Socket(qintptr handle, QObject *parent) : QTcpSocket(parent)
{
setSocketDescriptor(handle);
connect(this, &Socket::readyRead, [&]() { //4. co to za zapis [&]() ?
emit mReadyRead(this);
});
connect(this, &Socket::stateChanged, [&](int S) {
emit mStateChanged(this, S);
});
}