【C++】引用計數器簡單樣本

來源:互聯網
上載者:User

標籤:

//引用計數器  // 封裝一個計數器的類來維護,可以隱藏起來,即使用者不必關心是如何?的  #include <iostream>using namespace std;class String_Rep{friend class String;public:String_Rep(const char *str = " ") :count(0){m_data = new char[strlen(str) + 1];strcpy(m_data, str);}~String_Rep(){delete[]m_data;}public:void increment(){count++;}void decrement(){if (--count == 0){delete this;// 哪一個rep的count為0了釋放當時的rep  }}private:char *m_data;int count;};//////////////////////////////////////////////////////////////////////class String{public:String(const char *str = " ") :rep(new String_Rep(str)){rep->increment();}String(const String &s) :rep(s.rep){rep->increment();}String& operator=(const String &s){if (this != &s){rep->decrement();    // 迭代器  rep = s.rep;rep->increment();}return *this;}~String(){rep->decrement();}public:void print()const{cout << rep->m_data << endl;}private:String_Rep *rep;// 控制代碼  };int main(){String s1("hello");String s2;s2 = s1;String s3("world");String s4;s4 = s3;s1.print();s2.print();s3.print();s4.print();return 0;}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

【C++】引用計數器簡單樣本

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.