Why should one use std::string over c-style strings in C++?
c++, c-strings, string
Solution
- std::string manages its own memory, so you can copy, create, destroy them easily.
- You can't use your own buffer as a std::string.
- You need to pass a c string / buffer to something that expects to take ownership of the buffer - such as a 3rd party C library.
Problem
"One should always use std::string over c-style strings(`char *`)" is advice that comes up for almost every source code posted here. While the advice is no doubt good, the actual questions being addressed do not permit to elaborate on the why? aspect of the advice in detail. This question is to serve as a placeholder for the same. A good answer should cover the following aspects(in detail): - Why should one use `std::string` over c-style strings in C++? - What are the disadvantages (if any) of the practice mentioned in `#1`? - What are the scenarios where the opposite of the advice mentioned in `#1` is a good practice?