为字符串设置自定义分配器

Vla*_*ala 9 c++ string allocator

我知道我可以使用语法为矢量设置自定义分配器vector<T, Alloc>.有没有办法我可以为字符串做同样的事情?

GMa*_*ckG 12

是.所有字符串类都来自类模板basic_string,声明如下:

template <class charT, class traits = char_traits<charT>,
            class Allocator = allocator<charT> >
class basic_string;
Run Code Online (Sandbox Code Playgroud)

例如,std::string就是这样typedef basic_string<char> string;.

第三个模板参数是分配器,因此您可以执行以下操作:

typedef basic_string<char, char_traits<char>, my_allocator<char> > my_string;
Run Code Online (Sandbox Code Playgroud)

  • 注意:my_allocator不必是模板. (3认同)