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其本身就以实现智能指针机能。