Difference between c++ string append and operator

2019-02-24 02:45发布

Is there any noticeable difference between the two lines? My coworker says that using += is "faster" but I don't see why they should be any different:

string s1 = "hello";
string s2 = " world";

// Option 1
s1 += s2;

// Option 2
s1.append(s2);

To clarify, I am not asking about the usage differences between the two functions - I am aware that append() can be used for a wider variety of uses and that operator += is somewhat more specialized. What I care about is how this particular example gets treated.

2条回答
虎瘦雄心在
2楼-- · 2019-02-24 02:54

In Visual Studio 2017 operator += is an inline function, which calls append().

查看更多
Luminary・发光体
3楼-- · 2019-02-24 03:09

According to the standard concerning string::op+= / online c++ standard draft, I wouldn't expect any difference:

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

(1) Effects: Calls append(str).

(2) Returns: *this.

查看更多
登录 后发表回答