'Reusing a buffer provided as a parameter to Socket::BeginSendTo

I am developing a networking library and I have stumbled across an interesting problem. Since I want this library to be as efficient as possible, I am trying to minimize memory allocations, primarily trying to reuse the same buffer over and over again. Problem is best explained with the following pseudo-code:

// Buffer filled with data ready to be sent.
buffer = {0, 1, 2}

// Sending data stored in the buffer.
socket.BeginSendTo(buffer, ...)

// Reusing the same buffer for the next message...
buffer[0] = 7

Well, this all would be great - if it actually worked. This piece of code will actually not send {0, 1, 2}, but rather {7, 1, 2} since data was modified before it got the chance to be sent.

How can I reuse the buffer for the next message, but at the same time ensure that original data I provide to Socket::BeginSendTo is actually the data that will be sent?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source