D26.1.0 复制构造函数和拷贝赋值操作符

这是《Effective C++》中条款12的读书笔记。

copy构造函数和copy assignment操作符,称为copying函数。

通常情况下编译器有默认的构造函数和赋值操作符,这两个函数都可以将被拷对象的所有成员变量做一份拷贝。但是当程序员声明自己的copying函数的时候,编译器不再做默认的拷贝操作。

例如下面一个Customer类:

class Customer
{
public:
...
    Customer(const Customer& rhs);
    Customer& operator=(const Customer& rhs);
...
private:
    std::string name;
};

Customer::Customer(const Customer& rhs) : name(rhs.name)
{
    printf("Customer copy constructor");
}
Customer::Customer& operator=(const Customer& rhs)
{
    printf("Customer copy assignment operator");
    name = rhs.name;
    return* this
}

这里的Customer定义了自己的构造函数和赋值操作符。当在类中添加一个私有变量,问题逐渐浮现:

class Customer
{
public:
...
    Customer(const Customer& rhs);
    Customer& operator=(const Customer& rhs);
...
private:
    std::string name;
    Data lastTransaction;
};

此时如果没有的自定义构造函数中复制lastTransaction,编译器不会做出任何提示。很明显的是,你为class添加一个成员变量,就必须同时修改copying函数。

当有继承发生的时候,隐藏了一个更大的危机。例如:

class PriorityCustomer: public Customer
{
public:
    //...
    PriorityCustomer(const PriorityCustomer& rhs);
    PriorityCustomer& operator=(const PriorityCustomer& rhs);
    //...
private:
    int priority;
};

PriorityCustomer::PriorityCustomer(const PriorityCustomer& rhs) : priority(rhs.priority)
{
    printf("PriorityCustomer copy constructor");
}
PriorityCustomer::PriorityCustomer& operator=(const PriorityCustomer& rhs)
{
    printf("PriorityCustomer copy assignment operator");
    priority = rhs.priority;
    return *this;
}

PriorityCustomer的copying函数看起来好像复制了类内的每一样东西,但是PriorityCustomer还内涵它所继承的Customer成员变量,而那些成员变量却未被复制。当自己定义copying函数时,也必须复制其基类的成分,而这些成分往往是private,所以无法直接访问基类的private,应该让派生类的copying函数调用相应的基类函数。如下:

PriorityCustomer::PriorityCustomer(const PriorityCustomer& rhs) : Customer(rhs), priority(rhs.priority)
{
    printf("PriorityCustomer copy constructor");
}
PriorityCustomer::PriorityCustomer& operator=(const PriorityCustomer& rhs)
{
    printf("PriorityCustomer copy assignment operator");
    Customer::operator =(rhs);
    priority = rhs.priority;
    return *this;
}

当你编写一个copying函数时,需要确保:

1.复制所有local成员变量

2.调用所有base class内适当的copying函数

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值