Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reassign unique_ptr object with make_unique statements - Memory leak?

Tags:

I don't get what following statement would do (specially second line)?

auto buff = std::make_unique<int[]>(128);
buff = std::make_unique<int[]>(512);

Will the second call to make_unique followed by assignment operator will de-allocate memory allocated by first call, or will there be memory leak? Must I have to use buff.reset(new int[512]); ?

I've debugged it, but didn't find any operator= being called, nor any destructor be invoked (by unique_ptr).

like image 582
Ajay Avatar asked Jun 14 '16 08:06

Ajay


People also ask

What happens when unique_ptr goes out of scope?

unique_ptr. An​ unique_ptr has exclusive ownership of the object it points to and ​will destroy the object when the pointer goes out of scope.

Can unique_ptr be moved?

A unique_ptr does not share its pointer. It cannot be copied to another unique_ptr , passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. A unique_ptr can only be moved.

Do I need to delete unique_ptr?

An explicit delete for a unique_ptr would be reset() . But do remember that unique_ptr are there so that you don't have to manage directly the memory they hold. That is, you should know that a unique_ptr will safely delete its underlying raw pointer once it goes out of scope.


1 Answers

Move assignment operator is called, which does

if (this != &_Right)
{   // different, do the swap
    reset(_Right.release());
    this->get_deleter() = _STD move(_Right.get_deleter());
}

No leak here, as it does reset, which will deallocate.

like image 81
V. Kravchenko Avatar answered Oct 03 '22 20:10

V. Kravchenko