我有一台tcp服务器,它需要允许一个客户端随时连接到它。每当有新客户端连接时,必须删除旧会话并创建新会话。
现在,我正在这样做:
void TcpServer::start_accept() {
Logger::info("[TCPSERVER] TCP Server starting to accept", __LINE__, __FILE__);
if (session) { // check if there is any older session, if so..delete them
session = NULL;
delete session;
}
session = new TcpServerSession(io_service_);
acceptor_.async_accept(session->socket(), boost::bind(&TcpServer::handle_accept, this, session, boost::asio::placeholders::error));
}
因此,无论何时我想向客户端发送味精,都是这样的:
int TcpServer::sendMsgToClient(std::string msg) {
if (session)
session->sendMsgToClient(msg);
}
我想知道这样做是否正确?基本上,主要是删除指针并重新创建它。什么是最好的方法?
最佳答案
if (session) { // check if there is any older session, if so..delete them
session = NULL;
delete session;
}
这是完全错误的!清空
session
,泄漏当前存在的所有内容,然后泄漏delete
NULL
,这绝对不起作用。为了安全起见,在成功创建新会话之前,请勿
delete
旧会话。像这样:if (session) {
// Create and initialise the new session first
TcpServerSession* newSession = new TcpServerSession(io_service_);
// Don't know what this line does, but I assume it's important
acceptor_.async_accept(newSession->socket(), boost::bind(&TcpServer::handle_accept, this, newSession, boost::asio::placeholders::error));
std::swap(session, newSession); // Put the new one in place
delete newSession; // delete the old one.
}
实际上,这假定
async_accept
不抛出。如果可以,您可能需要小心删除newSession
,可能使用某种智能指针。关于c++ - cpp删除旧指针并重新初始化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19290015/