Join Bill Weinman for an in-depth discussion in this video Why build a string library?, part of C++ Building a String Library.
- Your C++ Development Environment comes with a very good string library as part of the C++ Standard. So why would you want to build your own? That's an excellent question and I'm glad you asked it. The C++ language includes both the original Standard C Library, and the C++ Standard Template Library, often abbreviated as STL. The STL includes a number of convenient container Classes, including a very powerful and flexible string Class, simply called string.
For many purposes, the STL string Class is perfectly acceptable. But when your system must fit in a small space, and squeeze every bit of performance out of a small, low power processor, you'll probably try to avoid the STL altogether. Fortunately, this is something C++ is very good at, and it's also not very difficult to do. C++ is a systems programming language, which means that it's often used to build systems that must be small, fast, and efficient. To show you how significant this can be, I compiled a simple Hello World program using three different types of strings.
A plain C-string, an STL string, and a string built with the library we'll build here, which I call BWString. The code is very simple. The only difference being the string declaration, and how it's passed to put C. In order to get some idea of the difference in size, I compiled this code using static libraries on a Linux system using GCC 4.9.2, the latest version available, at the time I recorded this. As expected, the C-string version is smallest at 804 K-bytes in size.
The STL version is largest at 1.4 Mb. And the BWString version is just a little bit larger than the C-string version at 906 K. 906 K is just 12.7% larger than 804 K, where 1.4 Mb is 55% larger. If size and performance is a critical consideration, and I really need the additional features of a good string class, a 12.7 increase in size is much easier to justify than a 55% increase.
My BWString Class doesn't provide all of the functionality of the STL class, but it does provide what I need for most purposes. Writing a string class also serves as an excellent learning exercise. Whenever I set out to learn a new language, I'll give myself a few exercises to perform as part of the learning process. A string library's often part of that process for me. You may also find it helpful in your learning process.