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.
Only way to leak the internal buffer of
std::vectoris to leak the vector itself. Example:But leaking memory is not a good idea in general.
In this case, the only solution is to make sure that the lifetime of the
std::vectoris longer than the usage of the buffer. A vector always releases the buffer it owns on destruction, and there is no way to extract ownership from it except into another vector.One way to achieve that is this:
You could use a pool allocator to avoid redundant allocations for each packet.
Example adapted form this answer (now that this question has shifted from leaking to transferring ownership, this is close to a duplicate). There's also an alternative suggestion in another answer to that same question which uses a custom allocator that "steals" the ownership