What is std::string and how does it differ from a C-string?
Short answer
std::string is a class that owns and manages a dynamically-sized sequence of characters, handling memory automatically, growth, and many operations (concatenation, search, substr). A C-string is a raw null-terminated char array with manual memory management and no bounds safety.
Advertisement
AModel answer
std::string is a class that owns and manages a dynamically-sized sequence of characters, handling memory automatically, growth, and many operations (concatenation, search, substr). A C-string is a raw null-terminated char array with manual memory management and no bounds safety. std::string is the safe, convenient default in C++.
std::string s = "hello";
s += " world"; // grows automatically
const char* c = "hi"; // C-string, manualReal-world example
Using std::string avoids buffer-overflow bugs common with fixed char[] buffers.
Likely follow-ups
- Who manages std::string's memory? | Why is std::string safer than char[]?
Related topics