我这样定义一个新的分配器:
template <class T>
class CodecAlloc: public std::allocator<T> {
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
CodecAlloc() {}
CodecAlloc(const CodecAlloc&) {}
pointer allocate(size_type n, const void * = 0) {
T* t = (T*) malloc(n * sizeof(T));
std::cout
<< " used CodecAlloc to allocate at address "
<< t << " (+)" << std::endl;
return t;
}
void deallocate(void* p, size_type) {
if (p) {
free(p);
std::cout
<< " used CodecAlloc to deallocate at address "
<< p << " (-)" <<
std::endl;
}
}
template <class U>
struct rebind { typedef CodecAlloc<U> other; };
};
如果我键入新的类型:
typedef std::basic_string<char, std::char_traits<char>, CodecAlloc<char>> String;
工作正常,已调用CodecAlloc :: allocate。但是现在有这样的界面:
void SetBinary(const std::string&)
它的参数是std :: string,类型String
不匹配。所以我用这种方式来构造std::string
std::string str = std::string("Hello !!", CodecAlloc<char>);
SetBinary(str)
但是未调用CodecAlloc分配器!!为什么?以及我应该如何解决这个问题。 SetBinary接口无法更改。 thks
所以,线