c++類自動產生的成員函數總覽和類比

來源:互聯網
上載者:User

#include <string.h><br />struct A<br />{<br />A(){}<br />A(const A& a){memcpy(this, &a, sizeof(A));}<br />~A(){}<br />A& operator =(const A& a){<br />if (this == &a){<br />return *this;<br />}<br />//Copy your codes from ~A() here, if ~A() is not empty. Do not call it.<br />memcpy(this, &a, sizeof(A));<br />return *this;<br />}<br />A* operator &() {return this;}<br />const A* operator &() const {return this;}<br />};<br />struct B: public A<br />{<br />B():A(){}<br />B(const B& b):A(){<br />memcpy((void*)((size_t)((void*)(this)) + sizeof(B) - sizeof(A)),<br />(void*)((size_t)((void*)(&b)) + sizeof(B) - sizeof(A)), sizeof(B) - sizeof(A));<br />}<br />~B(){}<br />B& operator = (const B& b){<br />//Use A:: to avoid virtual function!<br />A::operator = (b);<br />if (this == &b ){<br />return *this;<br />}<br />//Copy your codes from ~B() here, if ~B() is not empty.<br />//Direct calling is legal but it will automatic call ~A().</p><p>//The codes in the next line do not depend on codes in copy constructor B(const B& b),<br />//no matter whether it was redefined by users!<br />//Attention, we can't assert sizeof(char) == 1.<br />memcpy((void*)((size_t)((void*)(this)) + sizeof(B) - sizeof(A)),<br />(void*)((size_t)((void*)(&b)) + sizeof(B) - sizeof(A)), sizeof(B) - sizeof(A));<br />return *this;<br />}<br />operator A() const {//Attention, the overload can never be used!<br />return A(*((const A*)this));<br />}<br />};<br />int main()<br />{<br />A a1, a2;<br />a1 = a2;<br />B b1, b2;<br />b1 = b2;<br />b1 = b1;<br />a2 = b1;<br />(void)(&a1);<br />(void)(&b1);<br />(void)((A)b2);<br /> return 0;<br />} 

 

補充:有的朋友對處理自賦值先調用基類賦值函數的情況提出了疑問。這裡我給一個處理自賦值的例子,在出現自賦值的機率很低的時候,效率比主動判斷高。

 class Wilma { };
 
 class Fred {
 public:
   Fred()                : p_(new Wilma())      { }
   Fred(const Fred& f)   : p_(new Wilma(*f.p_)) { }
  ~Fred()                { delete p_; }
   Fred& operator= (const Fred& f)
     {
      Wilma* tmp = new Wilma(*f.p_);   // 如果異常在此處被拋出也沒有問題
      delete p_;
      p_ = tmp;
      return *this;
     }
 private:
   Wilma* p_;
 };

聯繫我們

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