C++中的垃圾回收和内存管理(续)

boost memory的gc_allocator的使用

首先编译生成boost-memory的库,由于生成的是.so的动态库,所以需要在运行程序之前,将库文件的路径添加到LD_LIBRARY_PATH中。

简单使用,
auto_alloc比较简单,可以使用默认的存储管理,
NS_BOOST_MEMORY::auto_alloc alloc;
而scope_alloc稍微复杂一点,使用block_pool管理存储单元。
NS_BOOST_MEMORY::block_pool recycle;
NS_BOOST_MEMORY::scoped_alloc alloc(recycle);
而在为变量申请空间时,使用宏定义,
int* intObj = BOOST_MEMORY_NEW(alloc, int)(10);
*intObj = 123;

基于gc allocator的STL的使用,
一般STL的容器使用模板定义的,如deque,
NS_BOOST_MEMORY::scoped_alloc alloc;
std::deque<int, stl_allocator<int> > s(alloc);

可以参考libs/examples/文件夹里面的代码。

auto_alloc,scope_alloc,block_pool都在NS_BOOST_MEMORY命名空间中,
BOOST_MEMORY_NEW这些辅助的宏定义在basic.hpp中,如

#define BOOST_MEMORY_ALLOC(alloc, Type)        
    ((Type*)(alloc).allocate(sizeof(Type)))
#define BOOST_MEMORY_NEW(alloc, Type)        
    ::new((alloc).allocate(sizeof(Type), BOOST_MEMORY_DESTRUCTOR(Type))) Type

对于带有参数的对象,可以支持吗?
因为BOOST_MEMORY_NEW是用new定义的,如定义MyClass如下,

class MyClass
{
public:
    int a;
    char s[12];
public:
    MyClass(int t, const char* p)
    {
        a = t;
        strcpy(s, p);
    }
    void Print()
    {
        printf("%d, %s
",a,s);
    }
};

那么使用BOOST_MEMORY_NEW(alloc, MyClass)(4,"abcd")的时候,替换为
new MyClass(4, "abcd"),所以多个参数也是可以用的,这样看的话,#define BOOST_MEMORY_ALLOC就不适合了。

原文地址:https://www.cnblogs.com/Frandy/p/cpp_boost_memory_usage.html