为什么std :: string的自定义分配器不起作用

问题描述 投票:0回答:1

我这样定义一个新的分配器:

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

c++ string allocator
1个回答
0
投票

所以,线

© www.soinside.com 2019 - 2024. All rights reserved.