網站首頁 編程語言 正文
我這個人總是喜歡在寫代碼時追求極致,比如總是糾結于變量的命名,內存的消耗,執行的效率,接口的便捷性,代碼的可擴展性。。。但很多時候需要在他們之間做取舍,這就導致我在編碼時經常陷入僵局,唉。。。真是程序員的可悲,為此幾年前我還專門將自己的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
相關推薦
- 2022-07-29 Golang學習之反射機制的用法詳解_Golang
- 2022-08-29 .NET?Core項目使用swagger開發組件_實用技巧
- 2022-09-14 React路由組件傳參的三種方式(params、search、state)_React
- 2022-05-24 Django基礎CBV裝飾器和中間件的應用示例_python
- 2022-10-08 Golang?Web?框架Iris安裝部署_Golang
- 2022-07-11 MongoDB分片方式及片鍵選擇
- 2022-05-13 數據結構學習筆記——順序存儲結構實現棧
- 2022-11-06 修改Nginx配置返回指定content-type的方法_nginx
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支