What's the difference between std::string and std::basic_string? And why are both needed?

C++Stl

C++ Problem Overview


What's the difference between std::string and std::basic_string? And why are both needed?

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

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).

Solution 3 - C++

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>.

Solution 4 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBenjView Question on Stackoverflow
Solution 1 - C++CB BaileyView Answer on Stackoverflow
Solution 2 - C++pmrView Answer on Stackoverflow
Solution 3 - C++ZansonView Answer on Stackoverflow
Solution 4 - C++Spyros MourelatosView Answer on Stackoverflow