Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying from raw pointer to smart pointer using memcpy

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!

like image 334
kzaiwo Avatar asked Nov 22 '25 10:11

kzaiwo


1 Answers

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);
like image 199
Sourabh Avatar answered Nov 24 '25 02:11

Sourabh