C++随笔(二)

1、拷贝函数:

当为一个继承类写构造函数的时候要注意不要忘记拷贝从基类继承而来的数据。

class PriorityCustomer::Customer

{

private:

Priority priority;

}

PriorityCustomer::Priority(const PriorityCustomer &rhs):Customer(rhs),priority(rhs.priority)

{

;

}

同样对于赋值运算符:

PriorityCustomer::operator=(const PriorityCustomer &rhs)

{

Customer::operator=(rhs);

priority = rhs.priority;

  return *this;

}

如果你发现拷贝构造函数和赋值构造函数有相似的代码,为了避免代码重复,可以定义一个私有的函数存放重复代码,不要用拷贝构造函数和赋值构造函数去调用彼此。

2、使用智能指针管理heap resources

void f()

{

std::auto_ptr<Investment>pInv(createInvestment());

//createInvestment();   //return ptr to dynamically allocated

//注意:不要使用多个auto_ptr指向同一个资源,这样资源会被重复析构

....

}

//使用以下智能指针就不会有这种问题,因为其会自动计算有多少个指针指向了同一个资源,就不会有重复析构的问题

void f()

{

std::tr1::shared_ptr<Investment>pInv(createInvestment());

...

}

//注意:不要在动态数组vector,string...上使用智能指针,because其本身就以实现智能指针机能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值