I am trying to convert a legacy C code to use smart pointers. And came across the following (just snippets to get me started):
MATRIX* cache;
---
cache = new MATRIX[numRow*numCol];
if (cache == NULL)
{
return FAIL;
}
---
memset(cache, 0, sizeof(MATRIX)*numRow*numCol);
---
memcpy(cache, matrix, sizeof(MATRIX)*numRow*numCol);
I tried to convert them to become like this:
std::unique_ptr<MATRIX[]> cache;
---
cache = std::make_unique<MATRIX[]>(numRow*numCol);
if (cache == NULL)
{
return FAIL;
}
---
cache.reset();
Is this correct? Any better way to write it? Also, I'm not sure how to do the memcpy C++ counterpart of
memcpy(cache, matrix, sizeof(MATRIX)*numRow*numCol);
matrix is just a raw pointer of type MATRIX*.
Any suggestions?? Thank you so much!
Your implementation is correct, but you don't have to call reset to do the cleanup of the memory. It will be handled automatically by the std::unique_ptr class, and to access unique pointer memory we can just use get method like the following:
cache.get();
Hence, your memcpy will look like
memcpy(cache.get(), matrix, sizeof(MATRIX)*numRow*numCol);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With