0

I am just curious about the implementation of c++ string +=.

Is there any performance penalty for this? Which one is supposed to be faster?

String a = "xxx";
a += "(" + "abcd" + ")"

or

String a = "xxx";
a.append("(");
a.append("abcd");
a.append(")");
4

3 回答 3

2

鉴于它们在标准中具有逐字相同的规范,很难设想一个合理的实现,其中它们的运行时成本会有所不同:

21.4.6 basic_string modifiers [string.modifiers]

21.4.6.1 basic_string::operator+= [string::op+=]

basic_string& operator+=(const basic_string& str);

1 效果:通话append(str.data, str.size()).

2 回报:*this

...

21.4.6.2 basic_string::append [string::append]

basic_string& append(const basic_string& str);

1 效果:通话append(str.data(), str.size()).

2 回报:*this.

于 2012-11-28T06:59:18.173 回答
0

+=如果操作员不是通过调用来实现的,我会感到非常惊讶append

事实上,SGI 的文档表明basic_string

basic_string& operator+=(const basic_string& s) 相当于append(s)

此外,代码如下:

basic_string& operator+=(const basic_string& __s) { return append(__s); }

http://www.sgi.com/tech/stl/string

于 2012-11-28T03:18:17.820 回答
0

它们之间没有区别,实际上+=运算符的实现只是调用append。我从 STL 代码中读取它。

于 2012-11-28T03:19:53.700 回答