C++类的复制控制 笔记

vector<string> svec;

 它的初始化过程:

编译器首先使用 string 默认构造函数创建一个临时值来初始化 svec,然后使用复制构造函数将临时值复制到
 svec 的每个元素。

 

The parameter of the copy constructor does not strictly need to be const, but it does need to be a reference. Explain the rationale for this restriction. For example, explain why the following definition could not work.
复制构造函数的形参并不限制为 const ,但必须是一个引用。解释这个限制的基本原理,例如,解释为什么下面的定义
不能工作。

Sales_item::Sales_item(const Sales_item rhs);
注意:这样的拷贝构造函数为什么行不通     提示:形参的初始化是怎样的

因为复制构造函数的形参并不限制为 const ,但必须是一个引用,而这里这个函数并没有覆盖默认的构造函数,所有编译器会自动生成一个合成的复制构造函数,在形参初始化的时候,它是利用合成的复制构造函数,所以在这个过程中会产生一个死循环.故产生错误.

赋值操作符的返回类型应该与内置类型赋值运算返回的类型相同(第 5.4.1 节
 )。内置类型的赋值运算返回对右操作数的引用,因此,赋值操作符也返回对同一类类型的引用。

 

三法则

A useful rule of thumb is that if a class needs a destructor, it will also need the assignment operator and a copy constructor. This rule is often referred to as the Rule of Three, indicating that if you need a destructor, then you need all three copy-control members.
如果类需要析构函数,则它也需要赋值操作符和复制构造函数,这是一个有用的经
验法则。这个规则常称为三法则
,指的是如果需要析构函数,则需要所有这三个复制控制成员。

 

重要概念

An important difference between the destructor and the copy constructor or assignment operator is that even if we write our own destructor, the synthesized destructor is still run. For example, we might write the following empty destructor for class Sales_item:
析构函数与复制构造函数或赋值操作符之间的一个重要区别是,即使我们编写了自己的析构函数,合成析构函
数仍然运行。

例如,可以为 Sales_item: 类编写如下的空析构函数:

class Sales_item

{
      public:
          // empty; no work to do other than destroying the members,
          // which happens automatically
           ~Sales_item() { }
          // other members as before
};

撤销 Sales_item
类型的对象时,将运行这个什么也不做的析构函数,它执行完毕后,将运行合成析构函数以撤销类的成员。合
成析构函数调用 string 析构函数来撤销 string 成员,string 析构函数释放了保存 isbn 的内存。
units_sold 和 revenue 成员是内置类型,所以合成析构函数撤销它们不需要做什么。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值