1、内存回收方式。
默认的shared_ptr以delete销毁所拥有的裸指针,然而在实际应用中,特别是网游服务器这种存在着大批量对象创建、销毁的工程,单一的销毁方式就不再适用了。毕竟在上述环境下,采用memory pool做内存管理会更好。而这样回收动作也需由自己来控制,不再是单单一个delete了事。
细看了shared_ptr的源码,它的删除动作是由以下代码做到的:
- template<class T> inline void checked_delete(T * x)
- {
- // intentionally complex - simplification causes regressions
- typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
- (void) sizeof(type_must_be_complete);
- delete x;
- }
ok, 一个模板函数,这样做起来就简单了,我们只需要根据自己的对象特化出一个自己的版本就行,如下:
- namespace boost
- {
- template<>
- inline void checked_delete(GameGroupUnit* GameGroup) // GameGroupUnit是自己的对象
- {
- GameGroup->~GameGroupUnit();
- GameGroupPool::SINGLETON::Instance().free(GameGroup); // 自定的回收内存方式.
- }
- };
2、操作符
通常选择shared_ptr,都会将其与stl container相结合使用。而stl很多泛型算法都需要容器所存对象的比较操作符。
我们避免将裸指针存入stl容器,就是因为裸指针无法提供所指对象的比较操作。
回头再来看下shared_ptr,它的源码中也没有提供比较操作符,那我们就自己做一个,如下:
- namespace boost
- {
- template<class T>
- inline bool operator< (const shared_ptr<T>& right, const shared_ptr<T>& left)
- {
- return *right < *left;
- }
- };