Can make STL string::c_str() return NULL when it has no string?

北城以北 提交于 2019-12-24 09:48:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!