2

我得到了一个自定义分配器,它实现了它自己的分配策略、它自己的 malloc/free 等。现在,我被要求将此自定义分配器与 STL 容器(无论是向量还是其他容器)一起使用。例如,我创建了一个类,my_stdAllocator它是一个符合ISO C++ 标准的接口。通过这个类,我调用我的分配器的方法。例如:

template <class T>
class my_stdAllocator {

    // ...other required stuff...

    // allocate 'num' elements of type T
    pointer allocate(size_type num, const_pointer = 0) {
        return static_cast<T*>(MYAllocator::instance()->malloc(num));
    }

    // deallocate memory at 'p'
    void deallocate(pointer p, size_type num=0) { 
        MYAllocator::instance()->free(p);
    }

    // initialize allocated memory at 'p' with value 'value'
    void construct(pointer p, const T& value) {   
        ::new ((void*)p) T(value);  
    }


    // destroy elements of initialized memory at p
    void destroy(pointer p) {
        p->~T();
    }

    // ...other required stuff...

} // end my_stdAllocator

自定义分配器通常就像一个魅力:它已经过广泛的测试,它肯定会提高性能,限制碎片等。当我将它用作 stl 容器的分配器时,(比如,一个向量)它有这种奇怪的行为它有时可以正常工作,而有时它会因段错误而崩溃。

举个例子,它正确地分配和释放一个向量char

typedef char TP;

int main(int argc, char* argv[]) { 

std::vector<TP, my_stdAllocator<TP> > vec;

std::string s ("Whatever string, no matter how long...");

std::string::iterator it;
for (it=s.begin(); it<s.end(); ++it)
    vec.push_back(*it);

...

在向量内按“手动”数字时可以

typedef double TP;

int main(int argc, char* argv[]) { 

std::vector<TP, my_stdAllocator<TP> > vec;

// "manual" push_back
vec.push_back(3.2);
vec.push_back(6.4);
vec.push_back(9.6);
vec.push_back(12.8);
vec.push_back(15.1);
vec.push_back(18.3);
vec.push_back(21.5);

...

通过循环插入元素时,它会因分段错误而停止:

typedef int TP;

int main(int argc, char* argv[]) { 

std::vector<TP, ff_stdAllocatorInst<TP> > vec;

for(unsigned int i=0; i<size; ++i)
    vec.push_back( (TP) i );

...

当为至少一定数量的元素保留空间时,它就像一个魅力:

typedef int TP;

int main(int argc, char* argv[]) { 

std::vector<TP, ff_stdAllocatorInst<TP> > vec;

vec.reserve(size);
for(unsigned int i=0; i<size+150; ++i)
    vec.push_back( (TP) i );

...

请注意,当使用像这样的新展示位置时,不会发生上述段错误:

void *p = MYAllocator::instance()->malloc(size);
std::vector<TP> *vec = new (p) std::vector<TP>
for(unsigned int i=0; i<size; ++i)
    vec->push_back( (TP) i );

...    

正如我已经说过的,自定义分配器已经过测试并且工作正常。我的类是 C++ 标准和自定义分配器之间的简单接口。我尝试使用 gdb 对其进行调试,但没有帮助:底层分配器没问题,我的代码中一定有一些错误,但我不明白哪里出了问题!

4

1 回答 1

12

在调用自定义分配器的malloc函数时,您需要乘以要分配的对象的大小:

pointer allocate(size_type num, const_pointer = 0) {
    return static_cast<T*>(MYAllocator::instance()->malloc(num*sizeof(T)));
}
于 2012-09-27T16:05:17.097 回答