https://blog.csdn.net/nou_camp/article/details/70195795
在上一篇博客中(C++智能指針(二))模擬實現了三種智能指針。?
其中最好的就是shared_ptr,但是這并不代表它就是最完美的,它也有問題,這個問題就是循環引用問題。下面用一段代碼來解釋說明循環引用問題。#include<memory>
struct ListNode
{shared_ptr<ListNode> _next;shared_ptr<ListNode> _prev;int _data;ListNode(int x):_data(x), _next(NULL), _prev(NULL){}~ListNode(){cout << "~ListNode()" << endl;}
};void test()
{shared_ptr<ListNode> ap1(new ListNode(10));shared_ptr<ListNode> ap2(new ListNode(20));ap1->_next = ap2;ap2->_prev = ap1;
}
int main()
{test();system("pause");return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
這就是shared_ptr的缺陷–循環引用問題?
為了解決循環引用的問題,引進了弱指針weak_ptr?
weak_ ptr是一種不控制所指向對象的智能指針,它指向由一個shared_ptr管理的對象。將一個weak_ptr綁定到一個shared_ptr 不會改變shared_ptr的引用計數?
測試代碼如下
#include<iostream>
using namespace std;
#include<memory>
struct ListNode
{weak_ptr<ListNode> _next;weak_ptr<ListNode> _prev;int _data;ListNode(int x):_data(x){}~ListNode(){cout << "~ListNode()" << endl;}
};void test()
{shared_ptr<ListNode> ap1(new ListNode(10));shared_ptr<ListNode> ap2(new ListNode(20));ap1->_next = ap2;ap2->_prev = ap1;
}
int main()
{test();system("pause");return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
仿函數:仿函數(functor),就是使一個類的使用看上去像一個函數。其實現就是類中實現一個operator(),這個類就有了類似函數的行為,就是一個仿函數類了。
template<class T>
struct Less
{bool operator()(const T& l, const T& r){return l < r;}
};
void Test2()
{Less<int>less1;cout << less1(1, 2) << endl;
}
int main()
{Test2();system("pause");return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
定制刪除器和空間分配器
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include<memory>
class FClose
{
public:void operator()(void* ptr){cout << "fclose" << endl;fclose((FILE*)ptr);}
};
class Free
{
public:void operator()(void* ptr){cout << "free" << endl;free(ptr);}
};void test()
{//定制刪除器shared_ptr<FILE>p1(fopen("test.txt", "w"), FClose());//定制刪除器和分配器shared_ptr<int> p2((int*)malloc(sizeof(int)), Free(), allocator<int>());
}
int main()
{test();system("pause");return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
智能指針總結?
智能指針可以提供對動態分配的內存安全而方便的管理,但這建立在正確的使用前提下。?
1.不使用相同的內置指針值初始化(或reset)多個智能指針。?
2.不delete get( )返回的指針。(p.get( )返回p中保存的指針。要小心使用,若智能指針釋放了其對象,返回的指針所指向的對象也就消失了)?
3.不使用get()初始化或reset另一個智能指針。?
4.如果使用get( )返回的指針,記住當最后一個對應的智能指針銷毀后,你的指針就變成無效了。?
5.使用智能指針管理的資源不是new分配的內存,記住傳遞給他一個定制的刪除器。