之前我有一篇文章《 C++
中讓對象的拷貝成為 顯式 的》,使用類似的技巧,可以避免字串加法中的臨時對象,也許是因為惰性,這個想法一直沒有訴諸實現,今天有空把它寫了出來。
先看看這段代碼:
std::string a = "A";std::string b = a + "B" + "C" + "D" + "E" + "F";
在C++11之前的標準 C++1998/2003 中,為了計算 b,這段代碼一共建立了 5 個臨時 std::string 對象。
實現代碼非常簡單:
#include <string>template<class String>class strjoin_helper {private: String v; typedef typename String::value_type char_t; typedef strjoin_helper me;public: template<class StrX> explicit strjoin_helper(const StrX& x) : v(x) {} template<class Char> explicit strjoin_helper(const Char* s, ptrdiff_t n) : v(s, n) {} operator String() const { return v; } me& operator+(const String& y) { v += y; return *this; } me& operator+(const char_t* y) { v += y; return *this; } me& operator+(const me& y) { v += y.v; return *this; } friend me operator+(const char_t* x, const me& y) { me t(x); t.v += y.v; return t; } friend me operator+(const String& x, const me& y) { me t(x); t.v += y.v; return t; }};template<class AnyString>strjoin_helper<AnyString> strjoin(const AnyString& x) { return strjoin_helper<AnyString>(x); }strjoin_helper<std::string> strjoin(const char* s) { return strjoin_helper<std::string>(s); }strjoin_helper<std::string> strjoin(const char* s, ptrdiff_t n) { return strjoin_helper<std::string>(s, n); }strjoin_helper<std::wstring> strjoin(const wchar_t* s) { return strjoin_helper<std::wstring>(s); }strjoin_helper<std::wstring> strjoin(const wchar_t* s, ptrdiff_t n) { return strjoin_helper<std::wstring>(s, n); }
點擊這裡查看完整代碼
使用的時候更簡單:
using namespace std;int main() { string a = "123_" + strjoin("") + "A" + "B" + strjoin("abc") + strjoin("012345", 4); cout << a << endl; return 0;}
用一個簡單的程式測一下效能,這個程式的輸出結果:
loop=1000000: fast[temp_cnt=2000002 time=0.715966] slow[temp_cnt=10000002 time=1.305356]
總結
strjoin 使用了兩個 C++1998 中鮮為人知的特性:
- 如 《C++ 中讓對象的拷貝成為 顯式 的》中所說,臨時對象可以被修改,但不能綁定到非常量引用上
- 臨時對象的生存期為整個運算式,而不是某個真子運算式