目录:
标准库中只提供两大类型指针:<头文件 memory>
1.共享式<shard_ptr>.辅助类<weak_ptr,bad_weak_ptr,enable_shared_from_this>
2.独占式<unique_ptr>.
应该摒弃C++98提供的智能指针auto_ptr.
<误区与切记:定义智能指针智能通过构造函数初始化或者调用成员方法>
shard_ptr<string> p;
p = new string("hello");错误用法
p.reset(new string("hello"));正确用法
1.共享式<shard_ptr>(注意,一般指向对象.指向数组的话,要自定义delete并且这里还给出了unique_ptr释放array的方法)
①自定义delete:
②关于Array和自定义delete的方法:
②weak_ptr
weak_ptr为shard_ptr的辅助类指针,解决回环问题.<不需要你理解什么是回环问题,如果你代码跟下面一样相互引用的话就用weak_ptr代替weak_ptr>
weak_ptr主要是配合share_ptr来实现应用计数,同时不会发生循环引用。
参考:http://www.cnblogs.com/TianFang/archive/2008/09/20/1294590.html
程序输出:
node()node()
~node()
~node()
请按任意键继续. . .
导致循环引用的情形
程序输出(只有创建对象,没有释放对象):node()
node()
请按任意键继续. . .
2..独占式<unique_ptr>.
插讲:
C++11中使用shared_ptr和unique_ptr管理动态数组
在C++11中,若使用shared_ptr管理一个动态数组,则需手动制定一个删除器。
auto sp = std::shared_ptr(new int[len], [](char *p){delete []p;});
但是这样每次手动指定有点麻烦,经过查阅资料,发现可以使用shared_ptr为动态数组创建一个工厂函数。
具体使用如下:
- #include <iostream>
- #include <memory>
- #include <string.h>
- using namespace std;
- template <typename T>
- shared_ptr<T> make_shared_array(size_t size)
- {
- //default_delete是STL中的默认删除器
- return shared_ptr<T>(new T[size], default_delete<T[]>());
- }
- int main()
- {
- auto sp_array = make_shared_array<char>(100);
- strcpy(sp_array.get(), "hello smart pointer");
- sp_array.get()[0] = 'a';
- cout << sp_array << endl;
- //使用原始指针完成相同的功能:
- auto str_array = new char[100];
- strcpy(str_array, "hello old pointer");
- str_array[0] = 'a';
- cout << str_array << endl;
- delete [] str_array;
- return 0;
- }
输出结果为:
aello smart pointer
aello old pointer
不过我们可以使用 sp.get()先获取原始指针,再对原始指针进行下标操作。
而unique_ptr对动态数组提供了支持,指定删除器是一个可选项。也可以直接使用下标操作:
- #include <iostream>
- #include <memory>
- #include <string.h>
- using namespace std;
- class mclass
- {
- public:
- mclass()
- {
- mem = new char[100];
- cout << "mclass constructor" << endl;
- }
- ~mclass()
- {
- delete [] mem;
- cout << "mclass deconstrucotr" << endl;
- }
- public:
- char *mem;
- };
- int main ()
- {
- std::unique_ptr<mclass[]> up (new mclass[2]);
- strcpy(up[0].mem, "hello unique_ptr");
- cout << up[0].mem << endl;
- return 0;
- }
程序的输出为:
mclass constructor
mclass constructor
hello unique_ptr
mclass deconstrucotr
mclass deconstrucotr
PS:智能指针只能释放它自己直接指向的内存,若上段代码中mclass类的析构函数中忘了对mem进行释放,依然会造成内存泄露。
原文转载自:http://blog.csdn.net/wks19891215/article/details/50992171