一些关于shared_ptr大部分也只阐述了其最基本的用法。
但当有大量的指针需要new时不免也会产生过多的碎片,自定义分配器是一个好的解决方法。
参考了下C++11的标准:
template<class Y, class D> shared_ptr(Y* p, D d);
template<class Y, class D, class A> shared_ptr(Y* p, D d, A a);
template <class D> shared_ptr(nullptr_t p, D d);
template <class D, class A> shared_ptr(nullptr_t p, D d, A a);
8 Requires: p shall be convertible to T*. D shall be CopyConstructible. The copy constructor and
destructor of D shall not throw exceptions. The expression d(p) shall be well formed, shall have
well defined behavior, and shall not throw exceptions. A shall be an allocator (17.6.3.5). The copy
constructor and destructor of A shall not throw exceptions.
9 Effects: Constructs a shared_ptr object that owns the object p and the deleter d. The second and
fourth constructors shall use a copy of a to allocate memory for internal use.
10 Postconditions: use_count() == 1 && get() == p.
11 Throws: bad_alloc, or an implementation-defined exception when a resource other than memory
could not be obtained.
12 Exception safety: If an exception is thrown, d(p) is called.
依着理解应该是这么回事:
template<typename T>
class M_Alloc
{
//TODO
//对分配器的要求没有细看,跳转的太多了。
};
template<typename T>
class M_Delete
{
//TODO
};
int* p = nullptr;
M_Delete d;
M_Alloc a;
std::shared_ptr<int,M_Delete,M_Alloc>(p,d,a);
不知道如此使用是否正确。
PS:boost::shared_ptr 没有用过