Is there any good reason to use C-strings in C++ nowadays? My textbook uses them in examples at some points, and I really feel like it would be easier just to use a std::string
A couple more memory control notes:
C strings are POD types, so they can be allocated in your application's read-only data segment. If you declare and define std::string
constants at namespace scope, the compiler will generate additional code that runs before main()
that calls the std::string
constructor for each constant. If your application has many constant strings (e.g. if you have generated C++ code that uses constant strings), C strings may be preferable in this situation.
Some implementations of std::string
support a feature called SSO ("short string optimization" or "small string optimization") where the std::string
class contains storage for strings up to a certain length. This increases the size of std::string
but often significantly reduces the frequency of free-store allocations/deallocations, improving performance. If your implementation of std::string
does not support SSO, then constructing an empty std::string
on the stack will still perform a free-store allocation. If that is the case, using temporary stack-allocated C strings may be helpful for performance-critical code that uses strings. Of course, you have to be careful not to shoot yourself in the foot when you do this.