使用 make_unique 语句重新分配unique_ptr对象 - 内存泄漏



我不明白以下语句会做什么(特别是第二行)?

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

分配运算符对 make_unique 的第二次调用是否会取消分配由第一次调用分配的内存,还是会出现内存泄漏?我必须使用buff.reset(new int[512]);吗?

我已经调试了它,但没有发现任何operator=被调用,也没有调用任何析构函数(通过unique_ptr)。

调用移动赋值运算符,它

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

这里没有泄漏,因为它会重置,这将解除分配。

这里没有内存泄漏,分配将释放与第一次分配关联的资源。在调试器中看不到它很可能意味着相关调用刚刚优化。如果您想查看它,请尝试使用 -O0 进行编译。

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

最新更新