For your student class, you have first name, last name and "cmp" - I've no idea what that's supposed to be. Clearly a student could have a first and/or last name longer than 20 characters, so by hardcoding an array of 20 elements you've already created a system that:
- has to bother to check all inputs to make sure no attempt is made to store more than 19 characters (leaving space for a NUL), and
- can't reliably print out any formal documents (e.g. graduation certificates) that require students' exact names.
If you don't carefully check all your input handling when modifying arrays, your program could crash, corrupt data and/or malfunction.
With std::string
, you can generally just let people type into whatever fields your User Interface has, or pick up data from files, databases or the network, and store whatever you're given, print whatever you're given, add extra characters to it without worrying about crossing that threshold etc.. In extreme situations where you can't trust your input sources (e.g. accepting student data over untrusted network connections) you may still want to do some length and content checks, but you'd very rarely find it necessary to let those proliferate throughout all your code the way array-bounds checking often needs to.
There are some performance implications:
- fixed length arrays have to be sized to your "worst supported case" size, so may waste considerable space for average content
- strings have some extra data members, and if the textual content is larger than any internal Short String Optimisation buffer, then they may use further dynamic memory allocation (i.e.
new[]
), and the allocation routines might allocate more memory than you actually asked for, or be unable to effectively reuse delete[]
d memory due to fragmentation
- if a
std::string
implementation happens to share a buffer between std::string
objects that are copied (just until one is or might be modified), then std::string
s could reduce your memory usage when there are multiple copies of the student struct
- but this probably only happens transiently and is only likely to help with very long strings
It's hard to conclude much from just reading about all these factors - if you care about potential performance impact in your application, you should always benchmark with your actual data and usage.
Separately, std::string
is intuitive to use, supporting operators like +
, +=
, ==
, !=
, <
etc., so you're more likely to be able to write correct, concise code that's easily understood and maintained.