问题
My project has legacy library which consider NULL pointer as empty string.
But when I get return data from std::wstring like this,
std::wstring strData;
const wchar* pStr = strData.c_str();
ASSERT(NULL == pStr); // ASSERT!!
pStr is not NULL but pointer which wstring point.
Can I make std::string return NULL when it has no string data? Now I wrap every str member variable like this :
const wchar* GetName() { // I hate this kinds of wrapping function
if (m_Name.empty())
{
return NULL;
}
return m_Name.c_str();
}
My working environment is Visual Studio 2008 sp1 in Windows
Thanks in advance.
回答1:
Since you only need that new behavior for interacting with that legacy library and not in all code (for example strlen()
will break if you pass a null pointer into it) your best bet is to use an utility function for providing proper behavior.
Something like you suggested:
const wchar* GetStringBody( const std::string& str )
{
if( str.empty() ) {
return 0;
}
return str.c_str();
}
and call it where necessary.
回答2:
template <typename Char_t, typename Traits_t, typename Allocator_t>
inline const Char_t* StrPtr(const std::basic_string<Char_t, Traits_t, Allocator_t>& aString) {
return (aString.empty() || !aString.front()) ? nullptr : aString.c_str();
}
template <typename Char_t>
inline const Char_t* StrPtr(const Char_t* aString) {
return (!aString || !*aString) ? nullptr : aString;
}
Use this general functions to convert strings to pointers. All NULL
or empty() / ""
strings return nullptr
while any 1+ length strings returns the proper pointer.
来源:https://stackoverflow.com/questions/3994630/can-make-stl-stringc-str-return-null-when-it-has-no-string