C++ 字符串附加和运算符 += 之间的区别
Difference between c++ string append and operator +=
这两条线有什么明显的区别吗?我的同事说使用 += 是 "faster" 但我不明白为什么它们应该有任何不同:
string s1 = "hello";
string s2 = " world";
// Option 1
s1 += s2;
// Option 2
s1.append(s2);
澄清一下,我不是在询问这两个函数之间的用法差异 - 我知道 append()
可以用于更广泛的用途,并且operator +=
更专业一些。我关心的是如何处理这个特定的例子。
根据 string::op+= / online c++ standard draft 的标准,我预计不会有任何差异:
basic_string& operator+=(const basic_string& str);
(1) Effects: Calls append(str).
(2) Returns: *this.
在 Microsoft STL 实现中,运算符 +=
是一个内联函数,它调用 append()
。这是实现,
- 字符串 (1):
string& operator+= (const string& str)
basic_string& operator+=(const basic_string& _Right) {
return append(_Right);
}
- c 字符串 (2):
string& operator+= (const char* s)
basic_string& operator+=(_In_z_ const _Elem* const _Ptr) {
return append(_Ptr);
}
- 字符(3):
string& operator+= (char c)
basic_string& operator+=(_Elem _Ch) {
push_back(_Ch);
return *this;
}
这两条线有什么明显的区别吗?我的同事说使用 += 是 "faster" 但我不明白为什么它们应该有任何不同:
string s1 = "hello";
string s2 = " world";
// Option 1
s1 += s2;
// Option 2
s1.append(s2);
澄清一下,我不是在询问这两个函数之间的用法差异 - 我知道 append()
可以用于更广泛的用途,并且operator +=
更专业一些。我关心的是如何处理这个特定的例子。
根据 string::op+= / online c++ standard draft 的标准,我预计不会有任何差异:
basic_string& operator+=(const basic_string& str);
(1) Effects: Calls append(str).
(2) Returns: *this.
在 Microsoft STL 实现中,运算符 +=
是一个内联函数,它调用 append()
。这是实现,
- 字符串 (1):
string& operator+= (const string& str)
basic_string& operator+=(const basic_string& _Right) {
return append(_Right);
}
- c 字符串 (2):
string& operator+= (const char* s)
basic_string& operator+=(_In_z_ const _Elem* const _Ptr) {
return append(_Ptr);
}
- 字符(3):
string& operator+= (char c)
basic_string& operator+=(_Elem _Ch) {
push_back(_Ch);
return *this;
}