#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_;
};