练习13.1:
如果一个构造函数的第一个参数是自身类类型的引用,且任何额外参数都有默认值,则此构造函数是拷贝构造函数
拷贝初始化不仅在我们用=定义变量时会发生,在下列情况下也会发生:
1、将一个对象作为实参传递给一个非引用对象的形参
2、从一个返回类型为非引用类型的函数返回一个对象
3、用花括号列表初始化一个数组中的元素或一个聚合类中的成员
练习13.2:声明非法,这是Sales_date类的拷贝构造函数,但是传递的参数是非引用类型的,调用此拷贝构造函数时要求拷贝其实参,但拷贝实参又要求调用拷贝构造函数,从而一直循环,直至资源用尽
练习13.3:
StrBlob类和StrBlobPtr类都为定义拷贝构造函数,编译器会定义合成的拷贝构造函数。
拷贝StrBlob对象时,调用拷贝构造函数,拷贝其成员data,使用智能指针shared_ptr的拷贝构造函数进行拷贝。对应内存的引用计数加1。
拷贝StrBlobPtr对象时,调用拷贝构造函数,拷贝成员wptr和curr,拷贝wptr时,使用weak_ptr的拷贝构造函数进行拷贝。弱拷贝,对应内存引用计数不变。拷贝curr时,curr是内置数据类型size_t,直接进行拷贝。
练习13.4:
Point global;
Point foo_bar(Point arg)
{
//Point local = arg拷贝构造
Point local = arg, * heap = new Point(global);
//*heap = local;拷贝构造
*heap = local;
//Point pa[4] = { local,*heap };拷贝构造
Point pa[4] = { local,*heap };
//return *heap;拷贝构造
return *heap;
}
练习13.5:
#include <iostream>
#include <string>
using namespace std;
class HasPtr
{
public:
HasPtr(const std::string& s = std::string()):
ps(new std::string(s)),i(0) { }
//拷贝构造函数
HasPtr(const HasPtr& hp): ps(new std::string(*hp.ps)),i(hp.i) { }
private:
std::string* ps;
int i;
};