可以让 STL string::c_str() 在没有字符串时返回 NULL 吗? [英] Can make STL string::c_str() return NULL when it has no string?

查看:34
本文介绍了可以让 STL string::c_str() 在没有字符串时返回 NULL 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目具有将 NULL 指针视为空字符串的旧库.

My project has legacy library which consider NULL pointer as empty string.

但是当我像这样从 std::wstring 得到返回数据时,

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 不是 NULL 而是 wstring 指向的指针.

pStr is not NULL but pointer which wstring point.

当没有字符串数据时,我可以让 std::string 返回 NULL 吗?现在我像这样包装每个 str 成员变量:

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();
}

我的工作环境是Windows 中的 Visual Studio 2008 sp1

My working environment is Visual Studio 2008 sp1 in Windows

提前致谢.

推荐答案

因为你只需要新的行为来与遗留库交互,而不是在所有代码中(例如 strlen() 会中断,如果你向它传递一个空指针)你最好的办法是使用一个效用函数来提供正确的行为.

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.

像你建议的那样:

const wchar* GetStringBody( const std::string& str )
{
    if( str.empty() ) {
         return 0;
    }
    return str.c_str();
}

并在必要时调用它.

and call it where necessary.

这篇关于可以让 STL string::c_str() 在没有字符串时返回 NULL 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆