这个item主要分析了防止对象自我赋值,利用copy-and-swap策略来解决。
写了小代码,其实在实际中大部分会简单写:
#include <iostream> #include<string> using namespace std; class Widget { public: Widget(int aData):m_Data(aData) { } virtual void Swap(Widget &aRhs) { int lTemp = aRhs.m_Data; aRhs.SetData(m_Data); m_Data = lTemp; } Widget& operator=(const Widget &aRhs) { Widget lTemp(aRhs); Swap(lTemp); return *this; } int GetData() const { return m_Data; } void SetData(int aData) { m_Data = aData; } private: int m_Data; }; class Drived: public Widget { void Swap(Drived &aRhs) { Drived lTemp(aRhs); aRhs = *this; *this = lTemp; } private: int m_DriveData; }; int main() { Widget lTest1(10); Widget lTest2(-10); lTest2 = lTest1; cout << lTest2.GetData() << endl; }