Consider following code:
cv::Mat currentFrame; // some proper frame with allocated memory
std::vector<uint8_t> storage;
{
cv::Mat m1 = currentFrame.clone();
cv::Mat m2 = m1;
const auto *m1ptr = reinterpret_cast<const uint8_t *>(&m1);
storage.insert(storage.end(), m1ptr, m1ptr + sizeof(cv::Mat));
m1.addref();
}
{
cv::Mat m3;
uint8_t *dstPtr = reinterpret_cast<uint8_t *>(&m3);
std::copy_n(storage.begin(), sizeof(cv::Mat), dstPtr);
}
In the first scope I am working with a cv::Mat
image, doing some copying to increase the refcount, and finally bitwise-serializing just the cv::Mat
header (96 bytes) into the vector storage
. Notice m1.addref()
, where I increase the refcount by 1, so to avoid memory deallocation, when m1
and m2
get deleted, and refcount would drop to 0. Between the scopes, there is no actual cv::Mat
pointing to allocated place in the memory, but the copy of such cv::Mat
exists in the storage.
Then I try to restore it, by deserializing it from the storage. m3
is now a copy of already gone m1
, it points to still allocated memory block, and refcount=1. So I would expect everything to work. But when we reach the end of the scope and destructor of m3
is called, I get invalid pointer exception. What is wrong with this design?