好用的C++ string Format“函數(shù)”介紹
我這個人總是喜歡在寫代碼時追求極致,比如總是糾結(jié)于變量的命名,內(nèi)存的消耗,執(zhí)行的效率,接口的便捷性,代碼的可擴展性。。。但很多時候需要在他們之間做取舍,這就導(dǎo)致我在編碼時經(jīng)常陷入僵局,唉。。。真是程序員的可悲,為此幾年前我還專門將自己的CSDN簽名改成了現(xiàn)在這樣。
今天我又帶來一個函數(shù),相比網(wǎng)上其他版本效率更高(不存在額外拷貝問題),使用更便捷(無需預(yù)先分配緩存)。
起初我設(shè)計的函數(shù)如下:相比網(wǎng)上其他的Format,特點是降低了內(nèi)存消耗,也提升了使用的便捷性,但帶來了執(zhí)行效率的下降,而更嚴(yán)重的是存在多線程隱患,不推薦使用。
const std::string& StrUtil::Format(const char* pszFmt, ...)
{
va_list body;
va_start(body, pszFmt);
int nChars = _vscprintf(pszFmt, body);
std::mutex mtx;
mtx.lock();
static std::string str; // 非線程安全,因此下面使用互斥鎖
str.resize(nChars + 1);
vsprintf((char*)str.c_str(), pszFmt, body);
mtx.unlock();
va_end(body);
return str; // 非線程安全
}
然后,我又設(shè)計出了第二個Format方案。上個方案之所以在函數(shù)內(nèi)部使用了static變量,是為了解決函數(shù)返回后變量“str”銷毀的問題,這也是能讓一個Format好用的關(guān)鍵問題所在——“如何能在函數(shù)返回后,構(gòu)建好的字符串仍然能夠在內(nèi)存短暫駐留”,如下(利用臨時對象特性保證內(nèi)存短暫駐留)
/*************************************************************************
** Desc : 好用的格式化字符串“函數(shù)”,使用方法:
** printf(StrUtil::Format("%,%s", "hello", "world").c_str());
** Param : [in] pszFmt
** : [in] ...
** Return : std::string
** Author : xktesla
*************************************************************************/
class StrUtil
{
public:
struct Format : std::string
{
public:
Format(const char* pszFmt, ...)
{
va_list body;
va_start(body, pszFmt);
int nChars = _vscprintf(pszFmt, body);
this->resize(nChars + 1);
vsprintf((char*)this->c_str(), pszFmt, body);
va_end(body);
}
private:
Format() = delete;
Format(const Format&) = delete;
Format& operator=(const Format&) = delete;
};
};
到此這篇關(guān)于好用的C++ string Format“函數(shù)”介紹的文章就介紹到這了,更多相關(guān)C++ string Format內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++詳細講解函數(shù)調(diào)用與Struct和CLass的區(qū)別
主調(diào)函數(shù)使用被調(diào)函數(shù)的功能,稱為函數(shù)調(diào)用。在C語言/C++中,只有在函數(shù)調(diào)用時,函數(shù)體中定義的功能才會被執(zhí)行,下面讓我們詳細來了解2022-05-05

