文章目錄
- unique_ptr概述
- unique_ptr常用操作
unique_ptr概述
uniue_ptr是一個獨占式的指針,同一個時刻, 就只能有一個unique_ptr指向這個對象(內存),unique_ptr的使用格式
unique_ptr<Class_Tyep> P_Name;
unique_ptr的常規初始化:
unique_ptr<int> p; 創建一個空的智能指針
unique_ptr<int> pi(new int);
- make_unique函數
make_unique函數是在C++14中引入的,使用了make_unique函數之后不能指定刪除器, 如果不需要使用刪除器, 盡量使用make_unique函數,他的效率高
unique_ptr<int> p = make_unique<int>(100);auto p2 = make_unique<string>("C++");
unique_ptr常用操作
- unique_ptr的初始化和賦值
unique_ptr<int> p1 = make_unique<int>(100);unique_ptr<int> p2(new int(200));// unique_ptr<int> p3(p1); 不支持定義時初始化
// p1 = p2; 不支持賦值操作// 支持移動語義unique_ptr<int> p3 = std::move(p2); // 移動過后, p2為空, p3指向原來p2指向的對象.
- release
release(): 放棄對指針的控制權, 切斷了智能指針和其所指向的對象的聯系
他會返回一個裸指針, 可以將返回的這個裸指針手工delete釋放, 也可以用來初始化另外一個智能指針.
unique_ptr<int> p1(new int(100));unique_ptr<int> p2(p1.release());// delete p1.release();if (p1 == nullptr) cout << "ha ha" << endl;cout << *p2 << endl;
- reset()
reset不帶參數: 釋放智能指針指向的對象, 將智能指針置空
unique_ptr<string> pstr(new string("C++"));pstr.reset();if (pstr == nullptr) cout << "指針為空" << endl;
reset帶參數, 釋放智能指針指向的對象, 并讓該智能指針指向新的對象
unique_ptr<string> pstr(new string("C++"));//pstr.reset();//if (pstr == nullptr) cout << "指針為空" << endl;unique_ptr<string> pstr1(new string("Java"));pstr.reset(pstr1.release());cout << *pstr << endl;
- = nullptr
= nullptr釋放智能指針指向的對象, 并將智能指針置空
unique_ptr<int> ps1(new int(200));ps1 = nullptr;
- 指向一個數組
unique_ptr<int[]> p(new int[10]());