1

I am writing some code for doing asynchronous i/o in c++. I have come across a very interesting problem. I am dealing with lower os level system calls on linux, and for reasons that are not pertinent to the question, I must use malloc to make a buffer. I dont want the user exposed api for my code to have to worry about calling free() or any of that nonsense, so I plan on using std::vector<std::byte> instead.

However I cannot seem to figure out a way to simply "swap" in the malloced buffer for the internal buffer that the vector will use. Of course the obvious thing to do is dont worry about swapping, and just copy the data into the vector, then free() the malloc'd buffer, however this has the obvious downside of an additional copy.

Is there any way to just "swap" the pointer that the vector will use with the buffer pointer, then just adjust the size value of the vector instead?

I could not figure out how to actually do the swap, because the allocator that std::vector uses is different than malloc, and thus likely calls something other than free().

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39

0 Answers0