views:

22

answers:

1

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.

A: 

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.

sharptooth