2010-10-22 49 views
1

我的項目有遺留的庫,它將空指針視爲空字符串。可以讓STL string :: c_str()在沒有字符串時返回NULL嗎?

但是,當我得到的std :: wstring的這樣的返回數據,

std::wstring strData; 
const wchar* pStr = strData.c_str(); 
ASSERT(NULL == pStr); // ASSERT!! 

PSTR不爲空,但是指針,wstring的點。

我可以讓std :: string在沒有字符串數據時返回NULL嗎? 現在我每包STR成員變量是這樣的:

const wchar* GetName() { // I hate this kinds of wrapping function 
    if (m_Name.empty()) 
    { 
     return NULL; 
    } 
    return m_Name.c_str(); 
} 

我的工作環境是 的Visual Studio 2008 SP1在Windows提前

感謝。

回答

1

由於你只需要一個新的行爲與傳統的圖書館沒有交互的所有代碼(例如,如果你傳遞一個空指針到它strlen()將打破),最好的辦法是使用一個效用函數提供適當的行爲。

喜歡的東西你建議:

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

,並調用它必要

0
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; 
} 

使用此通用函數將字符串轉換爲指針。全部NULLempty()/""字符串返回nullptr而任何1+長度的字符串返回正確的指針。

相關問題