Why does C++ provide std::string (a.k.a. std::basic_string<char>) instead of just recommending that users use std::vector<char> or have std::string derive from, contain, or be a typedef of std::vector<char>? std::string seems redundant to me.
This is especially true given that the Boost string algorithms library (
http://www.boost.org/doc/html/string_algo.html) seems general enough that it can operate on vector<char>:
s.push_back(' '); s.push_back('a'); s.push_back('b'); s.push_back('c'); s.push_back(' ');
trim(s); // boost
vector<char> s2; s2.push_back('z'); s2.push_back('z');
vector<char> s3; s3.push_back('a');
replace_first(s, s3, s2); // boost
Effective use of this technique just requires some additional convenience functions be defined to make the syntax nicer for strings. Most of these functions can be defined external to the string or vector class, as the Boost string algorithms library does above.
The most complete explanation I've found for making basic_string different is in STLport stl/_string.h (
http://www.stlport.org/) as copied below:
// Standard C++ string class. This class has performance
// characteristics very much like vector<>, meaning, for example, that
// it does not perform reference-count or copy-on-write, and that
// concatenation of two strings is an O(N) operation.
// There are three reasons why basic_string is not identical to
// vector. First, basic_string always stores a null character at the
// end; this makes it possible for c_str to be a fast operation.
// Second, the C++ standard requires basic_string to copy elements
// using char_traits<>::assign, char_traits<>::copy, and
// char_traits<>::move. This means that all of vector<>'s low-level
// operations must be rewritten. Third, basic_string<> has a lot of
// extra functions in its interface that are convenient but, strictly
// speaking, redundant.
// Additionally, the C++ standard imposes a major restriction: according
// to the standard, the character type _CharT must be a POD type. This
// implementation weakens that restriction, and allows _CharT to be a
// a user-defined non-POD type. However, _CharT must still have a
// default constructor.
The main reason given here seems to be just that the C++ standard says so. My question then is why is the C++ standard defined as such. Of course this doesn't prevent me at all from writing my own rather simple string framework based on std::vector<char> and submitting it to Boost or using it internally.
The reason I ask is that I was working on implementing my own string class recently:
http://www.math2.org/david/list/20060718This got me to thinking of why dedicate such effort instead of writing my own more general "vector" class and basing the string class on the vector class.