Nick Nick - 1 year ago 78
C++ Question

change pointer in std::unique_ptr without destroy it

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


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

How I can refactor this with

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 Source

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

auto old_ptr = unique.release();

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;

    return true;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download