日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

好用的C++?string?Format“函數(shù)”介紹_C 語(yǔ)言

作者:xktesla ? 更新時(shí)間: 2022-03-19 編程語(yǔ)言

我這個(gè)人總是喜歡在寫(xiě)代碼時(shí)追求極致,比如總是糾結(jié)于變量的命名,內(nèi)存的消耗,執(zhí)行的效率,接口的便捷性,代碼的可擴(kuò)展性。。。但很多時(shí)候需要在他們之間做取舍,這就導(dǎo)致我在編碼時(shí)經(jīng)常陷入僵局,唉。。。真是程序員的可悲,為此幾年前我還專門(mén)將自己的CSDN簽名改成了現(xiàn)在這樣。

今天我又帶來(lái)一個(gè)函數(shù),相比網(wǎng)上其他版本效率更高(不存在額外拷貝問(wèn)題),使用更便捷(無(wú)需預(yù)先分配緩存)。

起初我設(shè)計(jì)的函數(shù)如下:相比網(wǎng)上其他的Format,特點(diǎn)是降低了內(nèi)存消耗,也提升了使用的便捷性,但帶來(lá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è)計(jì)出了第二個(gè)Format方案。上個(gè)方案之所以在函數(shù)內(nèi)部使用了static變量,是為了解決函數(shù)返回后變量“str”銷毀的問(wèn)題,這也是能讓一個(gè)Format好用的關(guān)鍵問(wèn)題所在——“如何能在函數(shù)返回后,構(gòu)建好的字符串仍然能夠在內(nèi)存短暫駐留”,如下(利用臨時(shí)對(duì)象特性保證內(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;
	};
};

原文鏈接:https://blog.csdn.net/xk641018299/article/details/122153434

欄目分類
最近更新