Effective C++ 2nd Edition (4)

十一. 如果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!

这样避免了内存泄漏了

可见,只有当一个类被用来作为基类的时候,才会把析构函数写成虚函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值