auto_ptr
是什么
一個類模板,解決delete發(fā)生之前發(fā)生異常從而導(dǎo)致內(nèi)存泄露的問題。
使用時需要包含memory頭文件。
void f() {int *ip = new int(42);...//如果這里發(fā)生異常,則下面的delete可能不會執(zhí)行,導(dǎo)致內(nèi)存泄露。delete ip; }????? #include <iostream> #include <memory> using namespace std;void f() {auto_ptr<int> ap(new int(42));//無需delete,發(fā)生異常時,超出f的作用域就會釋放內(nèi)存。 }int main() {return 0; }接受指針的構(gòu)造函數(shù)為explicit構(gòu)造函數(shù),不能使用隱式類型轉(zhuǎn)換。
auto_ptr<int> pi = new int(1024);???? //這是錯誤的。
auto_ptr<int> pi(new int(1024));????? //這是正確的。
賦值和復(fù)制是破壞性操作
auto_ptr<string> ap1(new string(“hello”));
auto_ptr<string> ap2(ap1);
所有權(quán)轉(zhuǎn)移,ap1不再指向任何對象!
?
測試auto_ptr對象是否為空時,要使用get成員。
如auto_ptr<int> p_auto;
//下面錯誤。
if (p_auto)
??? *p_auto = 1024;
?
//下面正確。
if (p_auto.get())
??? *p_auto = 1024;
?
不能直接將地址給auto_ptr對象,要使用reset成員。
如
p_auto = new int(1024);? //error
p_auto.reset(new int(1024));//right
?
auto_ptr只能管理從new返回的指針
如
int ix = 1024, *p1 = &ix, *p2 = new int(2048);
auto_ptr<int> ap1(p1); //error
auto_ptr<int> ap2(p2); //right
轉(zhuǎn)載于:https://www.cnblogs.com/helloweworld/archive/2013/05/07/3064223.html
總結(jié)
- 上一篇: 海尔空调加氟多少钱一次?
- 下一篇: 基本数据结构----循环链表