避免臨時對象的字串加法

來源:互聯網
上載者:User

之前我有一篇文章《 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 中鮮為人知的特性:

  1. 如 《C++ 中讓對象的拷貝成為 顯式 的》中所說,臨時對象可以被修改,但不能綁定到非常量引用上
  2. 臨時對象的生存期為整個運算式,而不是某個真子運算式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.