MEMO blog

主に自分用のメモです

【c++】std::unique_ptr

unique_ptrを使い出したがよく混乱するので記録する

#include <memory>

void func(){

    //オブジェクト
    //std::unique_ptr<T> uniptr(new T(val));
    //auto uniptr = std::make_unique<T>(val);
    std::unique_ptr<int> uniptr_int01(new int(10));
    auto uniptr_int02 = std::make_unique<int>(10);

    //配列
    //std::unique_ptr<T[]> uniptr_array(new T[N]);
    //auto uniptr_array = std::make_unique<T[]>(N);
    std::unique_ptr<int[]> uniptr_array_int01(new int[10]);
    auto uniptr_array_int02 = std::make_unique<int[]>(10);

}

make_unique()を使うときに、ついついnewしてしまってコンパイラさんに怒られます。。。

make_unique()の利点は:

  • autoが使える点(コンストラクタ呼び出しでないので)
  • new失敗時のリークリスク回避

逆にmake_unique()使用だと、カスタムDeleterの指定ができなくなるよう。

参考サイト: