循环引用
#include <iostream>
#include <memory.h>
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
using namespace std;
template<class T>
struct ListNode
{
ListNode(const T& data)
:_prev(NULL)
,_next(NULL)
,_data(data)
{
cout<<"ListNode()"<<endl;
}
~ListNode()
{
cout<<"~Node()"<<this<<endl;
}
shared_ptr<ListNode> _prev;
shared_ptr<ListNode> _next;
T _data;
};
void Test()
{
shared_ptr<ListNode> p1(new ListNode());
shared_ptr<ListNode> p2(new ListNode());
cout<<"p1->Count:"<<p1.use_count()<<endl;
cout<<"p2->Count:"<<p2.use_count()<<endl;
p1->_next = p2;
p2->_prev = p1;
cout<<"p1->Count:"<<p1.use_count()<<endl;
cout<<"p2->Count:"<<p2.use_count()<<endl;
}
使用shared_ptr时,由于节点之间的相互引用使得多个节点指向同一块空间,引用计数count不为1。在释放空间时,p1等待p2释放,而p2又在等待p1的释放,从而引起循环引用问题,造成内存泄漏。
仿函数:也叫函数对象。就是使一个类的使用看上去像一个函数。其实现原理就是就是在类中重载(),这个类就有了类似函数的行为,同时也成为一个仿函数类了
下面两个仿函数的使用例子
定制删除器
#include <iostream>
using namespace std;
template<class T>
struct Delete
{
void operator ()(T* p)
{
delete(p);
cout<<"Delete"<<endl;
}
};
template<class T>
struct Free
{
void operator ()(T* p)
{
free(p);
cout<<"Free"<<endl;
}
};
template<class T>
struct Fclose
{
void operator ()(T* p)
{
fclose(p);
cout<<"Fclose"<<endl;
}
};
template<class T, class Del = Del<T>>
class SharedPtr
{
public:
SharedPtr(T* p =NULL)
:_p(p)
,_pcount(NULL)
{
if(_p)
_pcount = new int(1);
}
SharedPtr(const SharedPtr<T, Del>& sp)
:_p(sp._p)
,_pcount(sp._pcount)
{
(*sp._pcount)++;
}
SharedPtr<T, Del>& operator =(const SharedPtr<T, Del>& sp)
{
if(this != &sp)
{
Release();
_p = sp._p;
_pcount = sp._pcount;
(*sp._pcount)++;
}
return *this;
}
~SharedPtr()
{
Release();
}
T& operator *()
{
return *_p;
}
T* operator ->()
{
return _p;
}
private:
void Release()
{
if(_p && (--(*_pcount)) == 0)
{
Del()(_p);
delete _pcount;
_pcount = NULL;
}
}
T* _p;
int* _pcount;
};
int main()
{
SharedPtr<int, Free<int>> sp1((int*)malloc(sizeof(int)));
SharedPtr<int, Delete<int>> sp2(new int(1));
SharedPtr<FILE, Fclose<FILE>> sp3(fopen("test.txt", "wb"));
}
多重冒泡排序
#include <iostream>
using namespace std;
template<class T>
struct Great
{
bool operator ()(T& left, T& right)
{
return left > right;
}
};
template<class T>
struct Less
{
bool operator ()(T& left, T& right)
{
return left > right;
}
};
template<class T, class Compare>
void BubbleSort(T arr[], int len)
{
int i = 0;
int j = 0;
int flag = 0;
for(i = 0; i < len-1; i++)
{
flag = 0;
for(j = 0; j < len-1-i; j++)
{
if(Compare()(arr[j], arr[j+1]))
{
flag = 1;
swap(arr[j], arr[j+1]);
}
}
if(flag == 0)
break;
}
}
int main()
{
int arr1[] = {3, 7, 5, 2, 1, 9, 6, 4, 8};
int len1 = sizeof(arr1)/sizeof(arr1[0]);
BubbleSort<int, Great<int>>(arr1, len1);
int arr2[] = {3, 7, 5, 2, 1, 9, 6, 4, 8};
int len2 = sizeof(arr2)/sizeof(arr2[0]);
BubbleSort<int, Less<int>>(arr2, len2);
return 0;
}