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

學無先后,達者為師

網站首頁 編程語言 正文

好用的C++?string?Format“函數”介紹_C 語言

作者:xktesla ? 更新時間: 2022-03-19 編程語言

我這個人總是喜歡在寫代碼時追求極致,比如總是糾結于變量的命名,內存的消耗,執行的效率,接口的便捷性,代碼的可擴展性。。。但很多時候需要在他們之間做取舍,這就導致我在編碼時經常陷入僵局,唉。。。真是程序員的可悲,為此幾年前我還專門將自己的CSDN簽名改成了現在這樣。

今天我又帶來一個函數,相比網上其他版本效率更高(不存在額外拷貝問題),使用更便捷(無需預先分配緩存)。

起初我設計的函數如下:相比網上其他的Format,特點是降低了內存消耗,也提升了使用的便捷性,但帶來了執行效率的下降,而更嚴重的是存在多線程隱患,不推薦使用。

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; // 非線程安全
}

然后,我又設計出了第二個Format方案。上個方案之所以在函數內部使用了static變量,是為了解決函數返回后變量“str”銷毀的問題,這也是能讓一個Format好用的關鍵問題所在——“如何能在函數返回后,構建好的字符串仍然能夠在內存短暫駐留”,如下(利用臨時對象特性保證內存短暫駐留)

 
 
/*************************************************************************
** Desc     : 好用的格式化字符串“函數”,使用方法:
**				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

欄目分類
最近更新