在搜索了Google代码搜索之后(我应该先想到这个...),我找到了这个:
//tools-cgi.cpp
string safe_string (const char * s)
{
return (s != NULL) ? s : "";
}
将NULL
转换为空字符串。虽然这不是标准,但可能是特定STL实现中的某种扩展,这在答案中提到了。
没有标准的safe_string。你在那个回答中看到的safe_string来自于一个私有的STL扩展实用库。
搜索“stlext/stringext.h”,你会看到同样的库在另一个论坛的帖子中被引用。
并不存在名为std::safe_string
的东西。
这不是C++标准的一部分(但或许应该是?)
我一直在使用同样类型的辅助函数来避免 std::string 在 NULL char * 字符串时抛出异常。但它更像是这样的:
// defined somewhere else as ""
extern const char * const g_strEmptyString ;
inline const char * safe_string(const char * p)
{
return (p) ? (p) : (g_strEmptyString) ;
}
没有额外的开销,也不会崩溃。当我将一个char *字符串传递给std::string时,如果该字符串为空,那么它应该表现为一个空字符串。