1. 将Copy构造函数或copy Assignment操作符声明为private
2. 因为member函数和friend函数可以调用private函数,不去定义private函数,当调用时会获得一个链接错误
class HomeForSale00 { public:HomeForSale00() {}void GenerateHomeForSale00Member(){HomeForSale00 home00;HomeForSale00 home01;//HomeForSale00 home02(home00); //链接错误//home00 = home01; //链接错误 } private:friend void GenerateHomeForSale00Friend();HomeForSale00(const HomeForSale00&);HomeForSale00& operator=(const HomeForSale00&); private:uint32_t HomePrice; };void GenerateHomeForSale00Friend() {HomeForSale00 home00;HomeForSale00 home01;home00.HomePrice = 200;//HomeForSale00 home02(home00); //链接错误//home00 = home01; //链接错误 }void Test00() {HomeForSale00 home00;HomeForSale00 home01;//HomeForSale00 home02(home00); //private不可访问//home00 = home01; //private 不可访问 GenerateHomeForSale00Friend();home00.GenerateHomeForSale00Member(); }
1. 为了阻止copying动作设计Uncopyable的base class
2. 因为Uncopyable class不含数据,因此不一定得以public继承,以及Uncopyable class的析构函数为虚函数
class Uncopyable { protected:Uncopyable() = default;~Uncopyable() = default; private:Uncopyable(const Uncopyable&) = delete;Uncopyable& operator=(const Uncopyable&) = delete; };class HomeForSale01:private Uncopyable { public:HomeForSale01() {}void GenerateHomeForSale01Member(){HomeForSale01 home00;HomeForSale01 home01;//HomeForSale01 home02(home00); //链接错误//home00 = home01; //链接错误 } private:friend void GenerateHomeForSale01Friend();HomeForSale01(const HomeForSale01&);HomeForSale01& operator=(const HomeForSale01&); private:uint32_t HomePrice; };void GenerateHomeForSale01Friend() {HomeForSale01 home00;HomeForSale01 home01;home00.HomePrice = 200;//HomeForSale01 home02(home00); //链接错误//home00 = home01; //链接错误 }void Test01() {HomeForSale01 home00;HomeForSale01 home01;//HomeForSale01 home02(home00); //private不可访问//home00 = home01; //private 不可访问 GenerateHomeForSale01Friend();home00.GenerateHomeForSale01Member(); }int main() {Test00();Test01();return EXIT_SUCCESS; }