学无先后,达者为师

网站首页 编程语言 正文

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

作者:TheOldManAndTheSea 更新时间: 2022-05-13 编程语言

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

栏目分类
最近更新