7

An answer to one of my questions included the following line of code:

label = std::safe_string(name); // label is a std::string

The intent seems to be a wrapper around a string literal (so presumably no allocation takes place). I've never heard of safe_string and neither, apparently, has google (nor could I find it in the 98 standard).

Does anyone know what this is about?

Community
  • 1
  • 1
Motti
  • 110,860
  • 49
  • 189
  • 262

4 Answers4

8

After searching google code search (I should have thought of this first...) I found this:

//tools-cgi.cpp
string safe_string (const char * s)
{
    return (s != NULL) ? s : "";
}

Which converts NULLs to zero length strings. Although this is not standard it's probably some sort of extension in a specific STL implementation which was referred to in the answer.

Motti
  • 110,860
  • 49
  • 189
  • 262
6

There is no standard safe_string. The safe_string you're seeing in that answerer's response is from what looks like a private STL extensions utility library.

Google for "stlext/stringext.h" and you'll see the same library referenced in a post on another forum.

4

There is no such thing as std::safe_string

Nemanja Trifunovic
  • 24,346
  • 3
  • 50
  • 88
0

It is not part of C++ standard (but perhaps it should be?)

I have been using the same kind of helper function to avoid a std::string throw an exception with a NULL char * string. But it was more something like:

// defined somewhere else as ""
extern const char * const g_strEmptyString ;

inline const char * safe_string(const char * p)
{
   return (p) ? (p) : (g_strEmptyString) ;
}

No overhead, and no crash of a std::string when I feed it a char * string that could be NULL but that, in that particular case, should behave as an empty string.

paercebal
  • 81,378
  • 38
  • 130
  • 159
  • Use of "" creates a 1 byte literal object. If the compiler is not smart each one is different and thus could potentially bloat the code. I would suspect the compiler is smart enough to optimize this away and thus this is a false gain and complicates the code. – Martin York Oct 26 '08 at 15:13
  • 1
    I am uncomfortable with the idea of returning pointers or references to local objects, even if the compiler could be supposed to handle each case correctly (and make "" survive the return). – paercebal Oct 26 '08 at 17:42
  • The actuall function returns a std::string so there's no problem with returning a pointer, anyway string literals are stored in the data segment of the program so it's well-defined to return a pointer to a literal from a function. – Motti Oct 26 '08 at 19:23
  • In this case, you're right. My example was part of something larger: The empty string was reused elsewhere, as were other global constant objects (I have a global.hpp and global.cpp sources for these kind of global constant variables). – paercebal Oct 27 '08 at 11:20