006unique_ptr概述和常見操作
#include<iostream>
#include<cstdlib>
#include<string>
#include<vector>
#include <memory>
using namespace std;
class A
{
public:
A(){}
~A()
{
;
}
};
auto myFunction()
{
return unique_ptr<string>(new string("jisuanjiz"));
}
int main(void)
{
unique_ptr<int>p1;
if (p1==nullptr)
{
cout << "p1是空指針" << endl;
}
unique_ptr<int>p2(new int(34354));
unique_ptr<int>p3 = make_unique<int>(234);
auto p4 = make_unique<int>(200);
unique_ptr<string>p5(new string("jisuanjizuchengyaunli"));
unique_ptr<string>p8 = std::move(p5);
unique_ptr<string>p9(p5.release());
string *p10 = p9.release();
delete p10;
unique_ptr<string>p11(new string("dsfsdf"));
p11.reset(p5.release());
unique_ptr<int>p12(new int(234));
p12 = nullptr;
unique_ptr<int[]>pArray(new int[123]);
pArray[0] = 0;
pArray[1] = 0;
unique_ptr<A[]>pAA(new A[10]);
shared_ptr<string>p13 = myFunction();
system("pause");
return 0;
}
/*
*(1)unique_ptr獨佔式指針-對象的專屬所有權
*同一時刻智能有一個unique_ptr指向這個對象。當unique_ptr被釋放的時候,它所指向的對象也被銷燬。
* 1.常規初始化
* 2.
*(2)unique_ptr常用操作
* 2.1unique_ptr不支持的操作
* 2.2 移動語義
* 2.3release(),放棄對指針指向對象的控制權,返回裸指針,同時將智能指針置空。
* 返回的裸指針可以正常使用。
* 2.4reset()
* 不帶參數,釋放智能指針對象所佔的內存空間,並經智能指針置空
* 帶參數,釋放原來的內存空間,並且指向新對象
*
* 2.5 =nullptr釋放智能指針所指向的內存空間,並將智能指針置空
*
* 2.6指向一個數組
2.7get() 返回智能指針中返回的裸指針
* 2.8解引用 *獲取智能指針的對象,直接進行操作
* 2.9swap()交換兩個智能指針所指向的對象
* 2.10智能指針名字作爲if判斷條件
*
* 2.11 unique_ptr轉換成shared_ptr類型,轉換後賦值
* shared_ptr包含一個顯式的構造函數,
* 轉換的過程中會創建控制塊
*(3)
*
* unique_ptr是沒有控制塊的
*
*/