Chinaunix首页 | 论坛 | 博客
  • 博客访问: 367657
  • 博文数量: 38
  • 博客积分: 256
  • 博客等级: 入伍新兵
  • 技术积分: 846
  • 用 户 组: 普通用户
  • 注册时间: 2012-12-14 23:21
文章分类

全部博文(38)

文章存档

2015年(1)

2014年(1)

2013年(28)

2012年(8)

我的朋友

分类: C/C++

2013-02-03 22:02:35

在上一篇文章中,我给出了一个重载New/Delete的通用设计方法。但是当我们使用它时,会发现,它还是挺麻烦的,要修改三个地方:

a. 在.cxx文件中定义一个extern字符串;

b. 在.hxx文件中声明这个字符串;

c. 使目标类继承于模板类。

 

当我们设计一个lib的导出接口时,一个很重要的目标就是简化某个功能的使用方法,也就是说用户可以做最少的输入就可以得到某个功能。所以,在我发布那个设计之后,我还在持续的做改进。

这里我来告诉大家一个“one line” change 接口。

1. 如何使用:

struct MyClass{
MEM_POOL_SUPPORT(MyClass, sizeof(MyClass), “MyCass”)
………………..
};

2.  宏定义:

#define MEM_NEW0_DEFINITION(clientType, size, name)                                 \
    static void* operator new(size_t s) {                                           \
        static size_t lObjSize = size;                                              \
        Pool_assert(s <= lObjSize);                                                 \
        return MemPoolAllocator::allocate(lObjSize, name);              \
    }
#define MEM_POOL_SUPPORT(clientType, size, name)                    \
protected:                                                          \
    typedef MemPoolAllocator MemPoolType;               \
public:                                                             \
    MEM_NEW0_DEFINITION(clientType, size, name)                     \
    MEM_DELETE_DEFINITION(clientType)
#define SMALLPOOL_SUPPORT(clientType, size, name, preAllocNum)       \
protected:                                                           \
    typedef MemPoolAllocator MemPoolType;                \
public:                                                              \
    MEM_NEW1_DEFINITION(clientType, size, name, ulong32(preAllocNum))\
    MEM_DELETE_DEFINITION(clientType)
#define LARGEPOOL_SUPPORT(clientType, size, name, preAllocNum)          \
protected:                                                              \
    typedef MemPoolAllocator MemPoolType;                   \
public:                                                                 \
    MEM_NEW1_DEFINITION(clientType, size, name, boolean_t(preAllocNum)) \
    MEM_DELETE_DEFINITION(clientType)
 

3. MemPoolAllocator 定义

template
class MemPoolAllocator {
public:
    static void* allocate(size_t size, char const *name);
    static void* allocate(size_t size, char const *name, ulong32 preAllocNum);
    static void* allocate(size_t size, char const *name, boolean_t usePLA);
    static void  release(void *p);
    static Pool *getOwnedMemPool();
private:
    static Pool*            mPrivatePool;
    static Sthread_MutexSpl mLock;
};

 相比于上次的那个template,这次,我结合了template和MACRO。你们可以看出,这个设计的使用限制更少,可以应用于更多的场合。

 做为一个C++工程师,懂得并理解C++提供的各种编程范式和编程特性,是很重要的。但是更重要的是,懂得何时何地使用它们。如果把一个特性使用错了地方,那么它不仅不会给你的设计增色,而且会给你带去更大的麻烦。

阅读(1622) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~