Zero-overhead principle(零开销抽象)

The zero-overhead principle is a C++ design principle that states:

  1. You don't pay for what you don't use.
  2. What you do use is just as efficient as what you could reasonably write by hand.

In general, this means that no feature should be added to C++ that would impose any overhead, whether in time or space, greater than a programmer would introduce without using the feature.

The only two features in the language that do not follow the zero-overhead principle are runtime type identification and exceptions, and are why most compilers include a switch to turn them off.

总结下知乎大佬的回答:

// 解引用一个unique_ptr 和 解引用一个裸指针T*在汇编或者机器指令层面是完全相同的,unique_ptr // 对象所在的内存地址,就等于它的成员T*所在的内存地址。这一块8字节(假设64位系统)的内存解释为一个 // unique_ptr对象还是一个指针T*在微观层面没有任何区别。

// unique_ptr 生命周期结束时需要调用析构函数完成被管理对象的delete操作,但是其作为模板类,析构
// 函数是可直接内联的,因此相比直接使用delete,并不会产生额外的函数调用的开销。考虑以下两种写法,运 // 行时开销完全相同

struct A; // 定义略

{
  std::unique_ptr a_unique_ptr(new A);
  // 对象离开作用域自动析构,unique_ptr的析构函数可直接内联展开为delete语句
}

{
  A* a_raw_ptr = new A;
  delete a_raw_ptr;  // 离开作用域前手动析构
}

你可能感兴趣的:(C++中高级特性,c++)