十一. 如果class内动态配置有内存,请为此class声明一个copy constructor和一个assignment运算符
简陋的string class
如果定义两个对象:
String("Hello");
String("World");
然后那
b=a;
因为operator=不存在,用默认的assignment运算符(条款45),一个位一个位逐次设值。。。
结果出现问题了。。。。
(1)b原来所指的内存没有被释放掉;memory leak了丫
(2)a和b内含指针指向相同字符串,离开scope时候那,destructor会删除内存,析构的时候删除2次,出错了。
十二 . 在constructor中尽量以initialization动作取代assignment动作
(1)类中const,reference成员变量必须要initialization动作操作;
(2)类的构造函数需要调用其基类的构造函数的时候必须要initialization动作操作;
这玩意只有一次调用,比assignment效率高一点。
另外提下,static class member绝不能在类的constructor里被初始化的。
十三. initialization list中的members初始化次序应该和其在class内声明的次序相同
理由嘛,没仔细看,反正记住这条就行了。呵呵
十四. 总是让base class拥有virtual destructor
还是看个例子吧
程序输出:
Do something in class Derived!
Output from the destructor of class Derived!
Output from the destructor of class Base!
Do something in class Derived!
Output from the destructor of class Base!
第八行前面加个 virtual 关键字
Do something in class Derived!
Output from the destructor of class Derived!
Output from the destructor of class Base!
Do something in class Derived!
Output from the destructor of class Derived!
Output from the destructor of class Base!
这样避免了内存泄漏了
可见,只有当一个类被用来作为基类的时候,才会把析构函数写成虚函数