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

我一直认为 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而new int[100]执行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 所述在评论中,请注意 std::make_unique() 之间的区别和 std::unique_ptr() - 见 Differences between std::make_unique and std::unique_ptr .

https://stackoverflow.com/questions/40635107/

相关文章:

c++ - 在 C++ 中设置本地环境变量

c++ - 向 Python 公开 C++ API

c++ - std::this_thread::yield() 与 std::this_thread

c++ - 如何轻松查看 C/C++ #include 图?

c++ - C 和 C++ 标准之间的关系是什么?

c++ - 为 Windows 编写超薄 C++ 程序(如 uTorrent)

c++ - 在函数模板中使用静态局部变量的地址作为类型标识符是否安全?

c++ - 架构 x86_64 : Compiling problems 的 undefined s

c++ - 我真的需要为 const 对象实现用户提供的构造函数吗?

c++ - 标准的 atomic bool 和 atomic flag 之间的区别