我正在开发一个使用IOCP的客户端应用程序。
我的每个I/O数据类源自WSAOVERLAPPED:
class IoRequest : public WSAOVERLAPPED
{
...
};
当执行异步I/O操作时,我这样使用它:
{ // WSASend - this is done in my main thread.
IoRequest *pIoRequest = new IoRequest;
pIoRequest->SetSocket(m_socket);
pIoRequest->SetBuffer(vecCommandData);
pIoRequest->SetOperationType(OP_TYPE_SEND);
WSASend(m_socket, pIoRequest->GetWsaBuffer(), 1, NULL, 0, pIoRequest, NULL);
}
{ // WSARecv - this is done in my I/O worker thread.
GetQueuedCompletionStatus(m_hIocp, &dwNumberOfBytesTransferred, &ulCompletionKey, (LPOVERLAPPED*)&pIoRequest, INFINITE);
...
WSARecv(pIoRequest->GetSocket(), pIoRequest->GetWsaBuffer(), 1, NULL, &(pIoRequest->GetFlags()), pIoRequest, NULL);
...
}
我在工作线程例程中重用IoRequest实例。我想知道,使用std::shared_ptr而不是原始指针来管理我的每个I/O数据会有什么问题吗?
因此,对于WSASend(),类似于:
std::shared_ptr<IoRequest> spIoRequest(new IoRequest);
spIoRequest->SetSocket(m_socket);
spIoRequest->SetBuffer(vecCommandData);
spIoRequest->SetOperationType(OP_TYPE_SEND);
WSASend(m_socket, spIoRequest->GetWsaBuffer(), 1, NULL, 0, spIoRequest.get(), NULL);
干杯
除非您在某个地方有std::shared_ptr<IoRequest>
的活动实例,否则在完成处理程序收到它之前,您的IoRequest
将在发送例程结束时被释放。