用make_unique语句重新分配unique_ptr对象-内存泄漏? [英] Reassign unique_ptr object with make_unique statements - Memory leak?
本文介绍了用make_unique语句重新分配unique_ptr对象-内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不明白下面的语句会做什么(特别是第二行)?
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);
第二次调用 make_unique
分配运算符将取消分配第一次调用分配的内存,还是会发生内存泄漏?我必须使用 buff.reset(new 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]);
?
我已经调试了它,但没有找到任何 operator =
被调用,也没有调用任何析构函数(通过 unique_ptr
)。
I've debugged it, but didn't find any operator=
being called, nor any destructor be invoked (by unique_ptr
).
推荐答案
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());
}
收益率汇编:
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
这篇关于用make_unique语句重新分配unique_ptr对象-内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文