Difference between c++ string append and operator +=

萝らか妹 提交于 2019-12-19 17:45:42

问题


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.


回答1:


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.




回答2:


In Microsoft STL implementation, the operator += is an inline function, which calls append(). Here are the implementations,

  • string (1): string& operator+= (const string& str)
basic_string& operator+=(const basic_string& _Right) {
    return append(_Right);
}
  • c-string (2): string& operator+= (const char* s)
basic_string& operator+=(_In_z_ const _Elem* const _Ptr) {
    return append(_Ptr);
}
  • character (3): string& operator+= (char c)
basic_string& operator+=(_Elem _Ch) {
    push_back(_Ch);
    return *this;
}
  • Source: GitHub: Microsoft/STL


来源:https://stackoverflow.com/questions/45067263/difference-between-c-string-append-and-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!