代码之家  ›  专栏  ›  技术社区  ›  davewy

在不初始化值的情况下,建议使用数组类型的std::unique\u ptr?

  •  4
  • davewy  · 技术社区  · 7 年前

    #include <memory>
    
    void do_memory()
    {
      std::unique_ptr<int[]> ptr = std::make_unique<int[]>(50);
    
      int* ptr2 = new int[50];
      delete[] ptr2;
    }
    

    https://godbolt.org/g/c3gEfV ),我看到这两组指令的优化程序集不同,因为 make_unique 使_唯一 引入了一些不必要的开销。

    unique_ptr 到阵列(如上所示) 没有 自动值初始化?我已经用例如。

    std::unique_ptr<int[]> ptr = std::unique_ptr<int[]>(new int[50]);
    

    2 回复  |  直到 7 年前
        1
  •  5
  •   GManNickG    7 年前

    如果确实必须这样做,只需编写自己的函数:

    template <typename T>
    std::unique_ptr<T> make_unique_uninitialized(const std::size_t size) {
        return unique_ptr<T>(new typename std::remove_extent<T>::type[size]);
    }
    

    unique_ptr 直接:

    std::unique_ptr<T[]>(new T[size])  // BAD
    

    因为这通常不是例外安全的(出于您使用的所有常见原因 make_unique 首先,考虑具有多个参数和抛出异常的函数调用)。

        2
  •  3
  •   angleKH    3 年前

    C++20更新

    C++20介绍 std::make_unique_for_overwrite ,其工作原理与 std::make_unique ,但它执行默认初始化,而不是值初始化。