What's the difference between std::string and std::basic_string? And why are both needed?
What's the difference between std::string and std::basic_string? And why are both n开发者_StackOverflow社区eeded?
std::basic_string is a class template for making strings out of character types, std::string is a typedef for a specialization of that class template for char.
std::string is an instantiation of std::basic_string<T>:
typedef std::basic_string<char> string
std::basic_string is necessary to have a similar interface for all type of strings (wstring for example).
A std::string is an instantiation of the std::basic_string template with a type of char. You need both so that you can make strings of things besides char, such a std::basic_string<wchar_t> for a string of wide characters. Or if you want a string with 32 bit elements, std::basic_string<unsigned int>.
Just a small addition to whatever everyone else answered. As std::string is a specialization of basic_string it also default some other parameters except the char type .A basic_string can have a custom char type (e.g. basic_string can have wide_chars ) , a custom char_trait (e.g. basic_string can have wide chars but support every operation of normal chars) ,and a custom allocator ( a basic_string can have some extra infos packed with it for a custom debugger or a static memory management).
Usefulness
The std::string defaults all this parameters to reasonable values as on most cases you only need an std::string and that is it's usefulness. On the other hand whenever you need something more custom you have std::basic_string. So both have their different purposes
加载中,请稍侯......
精彩评论