Nick Nick - 2 months ago 9
C++ Question

change pointer in std::unique_ptr without destroy it

I have C++ code that uses raw pointer with C functions

malloc
,
free
and
realloc
.

I am thinking to change it to smart pointer, but I really want to keep the
realloc
functionality, because I believe it is much better than
new
, since it does not need to "move" the contents every time.

How I can refactor this with
std::unique_ptr
?

Here is some pseudo code (I realize this code is not 100% safe. In fact I never tried to compile it)

class Demo{
char *ptr;
Demo(size_t size) : ptr( malloc(size) ){}

bool resize(size_t size){
char *ptr_new = realloc(ptr, size);

if (ptr_new == nullptr){
return false; // fail
}

// here is tricky part with std::unique_ptr,
// ptr is already deleted...
ptr = ptr_new;

return true;
}
};

Answer

The way to reassign a pointer without deleting it is to use release():

auto old_ptr = unique.release();
unique.reset(new_ptr);

So in your code that would be something like:

struct free_deleter {
    void operator(void* p) const { free(p); }
};

std::unique_ptr<char, free_deleter> ptr; // NB: malloc must be paired with free, not delete

bool resize(size_t size) {
    char* ptr_new = realloc(ptr.get(), size);
    if (!ptr_new) {
        return false;
    }

    ptr.release();
    ptr.reset(ptr_new); 
    return true;
}
Comments