auto_ptr
是什么
一個類模板,解決delete發生之前發生異常從而導致內存泄露的問題。
使用時需要包含memory頭文件。
void f() {int *ip = new int(42);...//如果這里發生異常,則下面的delete可能不會執行,導致內存泄露。delete ip; }????? #include <iostream> #include <memory> using namespace std;void f() {auto_ptr<int> ap(new int(42));//無需delete,發生異常時,超出f的作用域就會釋放內存。 }int main() {return 0; }接受指針的構造函數為explicit構造函數,不能使用隱式類型轉換。
auto_ptr<int> pi = new int(1024);???? //這是錯誤的。
auto_ptr<int> pi(new int(1024));????? //這是正確的。
賦值和復制是破壞性操作
auto_ptr<string> ap1(new string(“hello”));
auto_ptr<string> ap2(ap1);
所有權轉移,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
轉載于:https://www.cnblogs.com/helloweworld/archive/2013/05/07/3064223.html
總結
- 上一篇: 海尔空调加氟多少钱一次?
- 下一篇: 基本数据结构----循环链表