Remap unique_ptr object with make_unique - memory leak?

I don’t understand what the next statement will do (especially the second line)?

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

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

I debugged it, but did not find any called operator= and did not call any destructor (via unique_ptr ).

+6
source share
3 answers

gcc 5.3:

 #include <memory> extern void emit(int*); int main() { // declare and initialise buf auto buff = std::make_unique<int[]>(128); // make_unique on the RHS returns a temporary // - therefore an r-value reference // therefore this becomes and operator=(unique_ptr&&) // (move-assignment) buff = std::make_unique<int[]>(512); // something to get the compiler to emit code emit(buff.get()); } 

gives the assembly:

 main: pushq %r12 movl $512, %edi pushq %rbp pushq %rbx call operator new[](unsigned long) ; <-- new (1) movl $64, %ecx movq %rax, %rbp xorl %eax, %eax movq %rbp, %rdi rep stosq movl $2048, %edi call operator new[](unsigned long) ; <<-- new (2) movl $2048, %edx xorl %esi, %esi movq %rax, %rdi movq %rax, %rbx call memset movq %rbp, %rdi call operator delete[](void*) ;<-- delete (1) movq %rbx, %rdi call emit(int*) movq %rbx, %rdi call operator delete[](void*) ;<-- delete (2) popq %rbx xorl %eax, %eax popq %rbp popq %r12 ret movq %rax, %r12 movq %rbp, %rbx .L3: movq %rbx, %rdi vzeroupper call operator delete[](void*) ;<-- handles a failed assignment movq %r12, %rdi call _Unwind_Resume movq %rax, %r12 jmp .L3 
+5
source

An assignment statement is called that executes

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

There is no leak, since it is reset, which will be freed.

+5
source

There is no memory leak, the assignment will free up resources associated with the first distribution. Not to see it in the debugger most likely means that the corresponding call was just optimized. Try compiling with -O0 if you want to see it.

+4
source

All Articles