Bulletmagnet Bulletmagnet - 1 month ago 4x
C++ Question

Is it safe to dereference end()?

I have a function with the following signature:

std::string f(const char *first, const char *last) {
std::string result;
std::for_each(first, last, some_lambda_which_appends_to_result);
return result;

and an overload for std::string which calls it:

std::string f(const std::string s) {
return f(&*s.begin(), &*s.end());
// The one below would assume that the string is not empty
// f(& s.front(), & s.front() + s.size());

However, this may be unsafe (dereferencing s.end() might be a red card offense in itself).
Is there a safe way to get a pointer to the beginning of characters and a one-past-the-end pointer (two null pointers would be fine in case of an empty string),
or do I have to write

std::string(const std::string& s) {
return s.empty() ? std::string() : f(& s.front(), & s.front() + s.size());


It's not safe to dereference end(). However, you can use either c_str() or data() to achieve what you need:

std::string(const std::string& s) {
    return f(s.data(), s.data() + s.size());