C 智慧型指標 auto ptr

2022-04-15 15:22:53 字數 1150 閱讀 3921

/*

auto_ptr是智慧型指引,可以自我銷毀而不像new出來的物件一樣需要呼叫delete銷毀。

auto_ptr賦值用引起所有權的交接,作為函式引數或返回值都會引起所有權的交接。

auto_ptr必須顯示初始化

auto_ptrp(new int(43)) //ok

auto_ptrp = new int(43) //error

auto_ptrp;

p = new int(43); //error

p = auto_ptr(43) //ok

auto_ptr的函式:

type* release() throw(); //將該auto_ptr設為null,並且返回該物件的位址

void reset(type *_ptr = 0); //用來接收所有權,如果接收所有權者已經擁有了物件,則必須先釋放該物件。其中_ptr是type型別的指標,它將會替換原來auto_ptr所擁有的指標。

type* get() const throw; //返回該類儲存的指標。

*/#include

#include

using

namespace

std;

class

int

; ~int( ) ;

intx;};

intmain( )

/*constructing 0x3e2be8 value: 5

constructing 0x3e4af8 value: 6

destructing 0x3e2be8 value: 5 //乙個auto_ptr只能指向乙個物件,所以在賦新值前先要銷毀舊的。

0 //呼叫release()後auto_ptr返回其儲存值,並賦空,

pi2 == pi3 //pi2與pi3都是原來pi儲存類的指標。

destructing 0x3e4af8 value: 6

*/

author: visaya fan

date: 2011-11-24 16:21:36

html generated by org-mode 6.33x in emacs 23

C 智慧型指標 auto ptr

智慧型指標 auto ptr vc版本 擁有權管理和轉移 當乙個智慧型指標給另乙個智慧型指標初始化的時候,兩個智慧型指標將會同時指向乙個空間,這樣在物件析構的時候,會導致一塊空間釋放多次的問題,所以乙個物件從始至終只能擁有乙個智慧型指標,這樣就保證不會乙個物件多次釋放的問題.我們讓指標給指標初始化的...

C 智慧型指標(auto ptr)

智慧型指標 在c 中使用堆記憶體是非常頻繁的操作,堆記憶體的申請和釋放都由程式設計師自己管理。使用普通指標,容易造成堆記憶體洩露,二次釋放等問題,使用智慧型指標能更好的管理堆記憶體。c 11中引入了智慧型指標的概念,方便管理堆記憶體。棧 堆區別 棧 系統開闢 系統釋放 堆 手動開闢 手動釋放 設計 ...

C 智慧型指標auto ptr

template class auto ptr 建構函式 templateinline auto ptr auto ptr t p pointee p 拷貝建構函式 templateinline auto ptr auto ptr auto ptr rhs pointee rhs.release t...