When should std::string be used over character arrays?

const char* is a throwback to C. I’d say that in decent C++, about the only use for it is in extern "C" APIs.

std::string has a number of advantages:

  1. It provides a constant-time size() function. Discovering the length of a const char* takes linear time.

  2. It is guaranteed to be valid. A const char* has to be checked for being null, and it is entirely possible to pass incorrect data – data missing a null terminator. Such an occurrence is pretty much guaranteed to result in a crash or worse.

  3. It is compatible with standard algorithms.

If you’re worried about performance impacts of having to create a std::string to call the function, consider taking the approach the standard library uses – change the function to take a pair of iterators instead. You can then provide a convenience overload taking a const std::string& delegating to the iterator-pair one.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)