为什么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()的输出几乎是smart_pointer()三倍呢?

由于std::make_unique<int[]>(100)执行值初始化,而new int[100]执行默认初始化 – 在第一种情况下,元素是0初始化(对于int ),而在第二种情况下元素保持未初始化。 尝试:

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

你会得到与std::unique_ptr相同的输出。

看看这个 ,例如, 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() 之间的区别 – 请参阅std :: make_unique和std :: unique_ptr之间的区别 。