c++中如果要申请资源一般用到new,最后释放资源delete,如果我们在delete之前就退出了函数呢,看下面的代码:
- #include <iostream>
- //#include <memory>
- using namespace std;
-
- void fun()
- {
- int *ptr = new int;
-
- if(ptr == 0)
- {
- delete ptr;
- return;
- }
-
- cout << "hello prt" << endl;
-
- delete ptr;
- }
-
- int main()
- {
- fun();
- return 0;
- }
这样我们就要多写一个delete,如果if有很多分支或者别情况呢。甚至有时候我们忘了delete呢,他将导致内存泄露。如果使用智能指针auto_ptr就不会出现这种情况了。
下面我们来看一个例子:
- #include <iostream>
- #include <memory>//auto_ptr 需要用到的头文件
- using namespace std;
-
- void fun(auto_ptr<int> ptr)
- {
- if (ptr.get() == NULL)
- {
- cout << "NULL" << endl;
- }
- else
- {
- cout << *ptr << endl;
- }
- }
-
- int main()
- {
- auto_ptr<int> ptr(new int);
- //auto_ptr<int> ptr = new int(11); //ERROR 注意智能指针不能使用这种赋值方式
- *ptr = 44;
- fun(ptr);
-
- //cout << *ptr << endl;
- if (ptr.get() == NULL)
- {
- cout << "delete" << endl;
- }
-
- return 0;
- }
编译后结果为 44 delete
很明显我们可以看到ptr被释放掉了。
注意,智能指针有拥有权转移的性质,ptr1给ptr2赋值后,ptr1就被delete掉了就不能再取他的值了。代码如下:
- #include <iostream>
- #include <memory>
- using namespace std;
-
- ostream& operator<< (ostream& otm , auto_ptr<int>& ptr)
- {
- if(ptr.get() == NULL)
- {
- otm << "NULL" << endl;
- }
- else
- {
- otm << *ptr << endl;
- }
-
- return otm;
- }
-
- int main()
- {
- auto_ptr<int> ptr1(new int(22));
- auto_ptr<int> ptr2;
-
- cout << ptr1 << endl;
- cout << ptr2 << endl;
-
- ptr2 = ptr1;
- cout << ptr1 << endl;
- cout << ptr2 << endl;
-
- return 0;
- }
编译后结果为22 NULL NULL 22
可以看到执行ptr2 = ptr1后ptr1指向了NULL。
如果我们不希望看到拥有权的改变那就要在声明是加const。拥有权不可以改变但你可以取他的值来赋值,例如:*ptr1 = * prt2。
下面附一份《c++标准程序库》中提供的auto_ptr的实现代码,看了下,跟《c++程序设计语言》中的差不多,但跟具体,据说比标准库的有一些改进。