網站首頁 編程語言 正文
C++ 減少臨時字符串對象的產生
flyfish
以std::string字符串相連為例
產生臨時字符串對象的寫法
#include
#include
int main(int argc, char *argv[])
{
std::string s1 = "a";
std::string s2 = "b";
std::string s3;
s3 = s1 + s2;
std::cout<<s3<<std::endl;
}
s3 = s1 + s2;的過程
1 operator+(const string&,const string&);
字符串連接運算。它由s1+s2觸發。
2 string::string(const char *);
構造函數。在operator+()中執行string result(buffer)會觸發此函數。
3 string::string(const string&);
我們需要一個臨時對象存儲operator+()的返回值。拷貝構造函數使用返回的result string時創建該臨時對象。
4 string::~string();
在operator+()函數退出之前,將銷毀生命期限于自己函數范圍內的result string對象。
5 string::operator=(const string&);
調用賦值運算符,將operator+()生成的臨時對象賦給左邊的對象s3。
6 string::~string();
銷毀返回值使用的臨時對象
避免產生臨時字符串對象寫法1
如果要減少內存使用,代碼就這樣寫,以三個字符串相連為例
#include
#include
int main(int argc, char *argv[])
{
std::string s1 = "a";
std::string s2 = "b";
std::string s3 = "c";
std::string s4 = s1 + s2 +s3;
std::cout<<s4<<std::endl;
}
編譯器使用s4而不是臨時對象來存儲。 s1 + s2 +s3的結果直接復制構造至s4對象中.所以沒有臨時對象。
避免產生臨時字符串對象寫法2
#include
#include
int main(int argc, char *argv[])
{
std::string s1 = "a";
std::string s2 = "b";
std::string s3 = "c";
std::string s4;
s4=s1;
s4+=s2;
s4+=s3;
std::cout<<s4<<std::endl;
}
參考《提高C++性能的編程技術》
原文鏈接:https://blog.csdn.net/flyfish1986/article/details/124511427
相關推薦
- 2022-02-19 AttributeError: ‘str‘ object has no attribute ‘dec
- 2022-08-01 Oracle停止數據泵導入數據的方法詳解_oracle
- 2022-09-14 Python定制類你不知道的魔術方法_python
- 2022-04-04 git: master (pre-receive hook declined)
- 2023-12-07 redis key
- 2022-08-19 python項目中requirements.txt的用法實例教程_python
- 2022-10-23 C#使用Task實現并行編程_C#教程
- 2022-06-25 基于Python實現五子棋游戲_python
- 最近更新
-
- 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同步修改后的遠程分支