007unique_ptr使用方法總結和智能指針概述
#include<iostream>
#include<cstdlib>
#include<string>
#include<vector>
#include <memory>
using namespace std;
unique_ptr<string>myFunction()
{
unique_ptr<string>pr(new string("dsfsdf"));
return pr;
/*
* 從函數返回一個局部對象,系統給我們生成一個臨時unique_ptr對象,調用unique_ptr的移動構造函數
*
*/
}
void myDelete(string *pdel)
{
delete pdel;
pdel = nullptr;
}
typedef void(*myf)(string *);
//定義函數指針類型 using myf=void(*)(string*)
//typedef decltype(myDelete)*myf;
//lambda表達式
auto mydel=[](string*del)
{
delete del;
del = nullptr;
};
int main(void)
{
unique_ptr<string> p1;
p1 = myFunction();//臨時對象直接構造在p1中。不接受會釋放掉臨時對象及其所指向的內存空間。
//指定刪除器--取代系統默認的刪除器
unique_ptr<string, myf> p2(new string("jisuanj"), myDelete);
//另一種寫法
unique_ptr<string, decltype(myDelete)*>p3(new string("jisann"), myDelete);
//用lambda表達式來寫,可以理解成帶有operator()類型的類對象
unique_ptr<string, decltype(mydel)>p4(new string("sdfdsf"), mydel);
//unque_ptr和裸指針相同
string *p = nullptr;
cout << sizeof(p) << endl;//4
unique_ptr<string>p5(new string("sdf"));
cout << sizeof(p5) << endl;//4
system("pause");
return 0;
}
/*
*(1)返回unique_ptr智能指針
*是不能拷貝,要被銷燬的時候,還是可以拷貝的,最常見的是從一個函數返回一個unique_ptr
*
*(2)指定刪除器
* 1.缺省情況下,會用delete釋放內存空間
* unique_ptr<指定的對象類型,刪除器>智能指針變量名。
* 刪除器本質上是一個可調用對象。
* shared_ptr刪除器直接在參數裏面加上函數名字即可。但是unique_ptr的刪除器相對負載一點。
* 需要向類模板中傳遞具體類型和刪除函數類型。
unique_ptr<string, myf> p2(new string("jisuanj"), myDelete);
*
* 2.指定刪除器額外說明
* shared_ptr指定的刪除器不同,但是指向的對象類型相同,兩個shared_ptr就是同一種類型。
* 但是unique_ptr的類型包含刪除器,也就說,刪除器不同,unique_ptr不是同一個類型。
*
*(3)尺寸問題
* shared_ptr是裸指針的2倍,但是unque_ptr和裸指針相同.但是刪除器不同可能佔用內存空間不同
* lambda --4字節,
* 函數指針類型--8字節
* 增加字節對效率有影響,自定義刪除器喲啊謹慎使用。
* shared_ptr不管指定什麼刪除器都是裸指針的2倍。
*
*(4)智能指針總結
* 4.1智能指針背後的設計思想
* 主要目的:幫助我們釋放內存,防止內存泄漏。
* 4.2auto_ptr爲什麼被廢棄? --設計問題,會默認轉移所有權
* c++98時代的智能指針,具有unique_ptr智能指針的一部分功能。
* 且不能在容器中保存,並不能從函數中返回。
* 雖然unique_ptr和auto_ptr都是獨佔式的,但是auto_ptr進行賦值操作=會默認轉移所有權。
* 建議:使用unique_ptr取代auto_ptr
*
* 4.3智能指針的選擇
* shared_ptr
* unique_ptr
* 如果程序有多個指針指向同一個對象,使用shared_ptr
* 如果不需要多個指針指向同一個指針,使用unique_ptr指針
*
*
*
*/