1

I'm working on a client application that uses IOCP.

My per I/O data class is derived from WSAOVERLAPPED:

class IoRequest : public WSAOVERLAPPED
{
...
};

And when performing asynchronous I/O operations, I use it like this:

{ // 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);
    ...
}

I reuse my IoRequest instance in my worker thread routine. I wonder, will there be any problem using std::shared_ptr instead of a raw pointer to manage my per I/O data?

So for WSASend(), something like:

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);

Cheers

4

1 回答 1

1

Unless you have a live instance of std::shared_ptr<IoRequest> somewhere, your IoRequest will be deallocated at the end of the sending routine before the completion handler receives it.

于 2012-08-06T21:49:56.110 回答