I am trying to keep data in a unordered map of vectors, using uint32_t addresses as keys. The vector need to be stored in the heap so I can still access the data even if the function goes out of scope. I did the allocation like this:
using vectorBuffer = std::vector<uint8_t>;
using I2cVectorMap = std::unordered_map<address_t, vectorBuffer>;
using I2cVectorEntry = std::pair<address_t, vectorBuffer>;
if(auto i2cIter = i2cVectorMap.find(address); i2cIter == i2cVectorMap.end()) {
vectorBuffer * receiveVector = new vectorBuffer(maxReplyLen);
i2cVectorMap.insert(I2cVectorEntry(address, *receiveVector));
}
else {
// Already in map. readjust size
vectorBuffer * existingVector = &i2cIter->second;
existingVector->resize(maxReplyLen);
existingVector->shrink_to_fit();
}
And the deallocation like this (as recommended by various sources, swapping the vector with an empty one):
// getting the address from another object.
address_t deviceAddress = i2cCookie->getAddress();
if(auto i2cIter = i2cVectorMap.find(deviceAddress); i2cIter != i2cVectorMap.end()) {
vectorBuffer().swap(i2cIter->second);
}
is this a correct implementation? I will pass the address to the map entry either to a driver function initiating a I2C transfer or to another object processing the data. I want to ensure that I don't have a memory leak.
Thanks a lot in advance !