栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ 减少临时字符串对象的产生

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ 减少临时字符串对象的产生

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 = 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而不是临时对象来存储。 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< 

参考《提高C++性能的编程技术》

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/846781.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号