读书人

boost:shared_ptr定做删除器

发布时间: 2013-12-04 17:21:02 作者: rapoo

boost::shared_ptr定制删除器
我的shared_ptr保存的是一些对话框指针,所以析构的时候需要调用dlg->DestoryWindow(); 有没有可能写成泛型的定制删除器呢?
比如:

template<class T>
void CustomDestroy(T *x)
{
if(x != NULL )
{x->DestroyWindow();delete x;x=NULL;}
};

求解答 boost shared_ptr 泛型
[解决办法]
c++11 的话,可以这样。shared_ptr 基本是从 boost 抄的,所以 boost 的应该也行。


#include <iostream>
#include <memory>

struct dialog_t { };

template<class T>
struct deleter_t
{
void operator () (T* x) const
{
if(x != NULL )
{
std::cout << __LINE__ << std::endl;
delete x;
x=NULL;
}
}
};

int main ()
{
auto const p = std::shared_ptr<dialog_t>(new dialog_t, deleter_t<dialog_t>{});
}

读书人网 >C++

热点推荐