为什么 unique_ptr 实例化编译成比原始指针更大的二进制文件?

Why does unique_ptr instantiation compile to larger binary than raw pointer?

我一直觉得 std::unique_ptr 与使用原始指针相比没有开销。但是,编译以下代码

#include <memory>

void raw_pointer() {
  int* p = new int[100];
  delete[] p;
}

void smart_pointer() {
  auto p = std::make_unique<int[]>(100);
}

g++ -std=c++14 -O3 生成以下程序集:

raw_pointer():
        sub     rsp, 8
        mov     edi, 400
        call    operator new[](unsigned long)
        add     rsp, 8
        mov     rdi, rax
        jmp     operator delete[](void*)
smart_pointer():
        sub     rsp, 8
        mov     edi, 400
        call    operator new[](unsigned long)
        lea     rdi, [rax+8]
        mov     rcx, rax
        mov     QWORD PTR [rax], 0
        mov     QWORD PTR [rax+392], 0
        mov     rdx, rax
        xor     eax, eax
        and     rdi, -8
        sub     rcx, rdi
        add     ecx, 400
        shr     ecx, 3
        rep stosq
        mov     rdi, rdx
        add     rsp, 8
        jmp     operator delete[](void*)

为什么 smart_pointer() 的输出几乎是 raw_pointer() 的三倍?

因为 std::make_unique<int[]>(100) 执行 value initialization while new int[100] performs default initialization - 在第一种情况下,元素初始化为 0(对于 int),而在第二种情况下,元素未初始化。尝试:

int *p = new int[100]();

您将获得与 std::unique_ptr.

相同的输出

例如,参见 this,其中指出 std::make_unique<int[]>(100) 等同于:

std::unique_ptr<T>(new int[100]())

如果你想要一个带有std::unique_ptr的非初始化数组,你可以使用1:

std::unique_ptr<int[]>(new int[100]);

1@Ruslan in the comments, be aware of the difference between std::make_unique() and std::unique_ptr() - See Differences between std::make_unique and std::unique_ptr所述。