Bulletmagnet Bulletmagnet - 1 year ago 99
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());

Answer Source

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());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download