tags:

views:

327

answers:

4

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?

+5  A: 

There is no such thing as std::safe_string

Nemanja Trifunovic
+6  A: 

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.

James D
The results of your search do not include "safe_string".
Motti
+6  A: 

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
A: 

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
Why do you need g_strEmptyString, doesn't "" do the trick.
Motti
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
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
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
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