I need to find a way to intentionally leak (take ownership of) the internal pointer of a std::vector
so that its lifetime surpasses the one of the original container and so that it can be later deleted manually.
Why? I'm working on a networked application using the C ENet library that needs to send large amounts of packets in a short amount of time.
I create network messages by writing the data to a std::vector<unsigned char>
.
Then in order to create a "packet," I use the enet_packet_create
function, which takes a pointer to a byte array to be sent and its size. In normal mode of operation, the function simply dynamically duplicates the given array on the heap, but there is also a "no allocate" option which only takes the pointer and size, leaving deleting to the creator using a callback function, and that's exactly what I'm trying to achieve -- the data is already there in the vector ready to be used, so there is no need to copy it again, as it could be costly.
You don't need to leak anything. Just use the
userData
field of theENetPacket
structure to store the to-be-deletedstd::vector
, and just delete it in the callback:}
The
userData
void pointer is a usual strategy to hold opaque user data and use it in callbacks, so the user of the library can retrieve the context in which the callback has been called.It can be anything (
void*
), from a state holder structure in order to do complex logic after the callback, or just a data pointer which needs to be freed like your case.From your comments, you say that you don't want to dynamically allocate the
vector
.Just remember that any data inside the vector has been dynamically allocated (unless a custom allocator has been used) and the
ENetPacket
structure has also been dynamically allocated (the passed flag just indicates not to allocate thedata
, not the structure)Finally, if you know (or can precompute) the size of the data, a different approach would be to create the packet passing a NULL data pointer.
The function
enet_packet_create
will create the data buffer, and you can just fill the data directly in the packet buffer, without needing a different buffer and then copying it to the packet.