c++ Primer 第13章 拷贝控制

个人笔记


概述

1)类的成员叫“资源”,指针,容器等。

2)类的行为像值:拷贝复制等,源和副本各有一份“资源”; 

      行为像指针:使用引用计数,共享底层数据。


1,行为像值得类

class HasPtr {
private:
	string* ps; //资源;
	int i;
public:
	HasPtr(const string& str = string()) : ps(new string(str)), i(0) {}
	HasPtr(const HasPtr& oth) : ps(new string(*oth.ps)), i(oth.i) {}
	HasPtr& operator=(const HasPtr& oth) { //如果把参数的&去掉,走的是拷贝构造;
		string* strTmp = new string(*oth.ps);
		delete ps;
		ps = strTmp;
		i = oth.i;
		return *this;
	}
	~HasPtr() { delete ps;}
};
<pre name="code" class="cpp">int _tmain()
{
	HasPtr ptr1("mao");
	HasPtr ptr2 = ptr1;  //走的是拷贝构造;

	HasPtr ptr3;
	ptr3 = ptr1;
}
 

 

2,行为像指针的类

class HasPtr2 {
private:
	string* ps;
	int i;
	size_t* use; //引用计数;
public:
	HasPtr2(const string& str = string()) : ps(new string(str)), i(0), use(new size_t(1)) {}  //构造一个就是1
	HasPtr2(const HasPtr2& oth) : ps(oth.ps), i(oth.i), use(oth.use) {
		++*use;  //拷贝一个就递增,ps是直接赋值oth.ps,没有new新资源;
	}
	HasPtr2& operator=(const HasPtr2& oth) {
		++*oth.use;
		if(--*use == 0) {
			delete ps;
			delete use;
		}
		//string* strTmp = new string(*oth.ps); //不用防止自我赋值,因为上面4行代码
		//delete ps;
		//ps = strTmp;
		ps = oth.ps;
		i = oth.i;
		use = oth.use;
		return *this;
	}
	~HasPtr2() {
		if(--*use == 0){ //引用计数为0才释放共享资源
			delete ps;
			delete use;
		}
	}
};

换成智能指针:

class HasPtr2 {
private:
	shared_ptr<string> ps;
	int i;
public:
	HasPtr2(const string& str = string()) : ps(make_shared<string>(str)), i(0) {} 
	HasPtr2(const HasPtr2& oth) : ps(oth.ps), i(oth.i){}
	HasPtr2& operator=(const HasPtr2& oth) {
		ps = oth.ps;
		i = oth.i;
		return *this;
	}
	~HasPtr2() {}
};

3,定义自己的swap

问题:swap(HasPtr& , HasPtr&) 调用默认swap执行两步拷贝。

HasPtr temp = v1;
v1 = v2;
v2 = temp;

这是一种多余,我们希望交互资源指针之类的正确操作。

重写自己的swap。

class HasPtr {
	friend void swap(HasPtr& lhs, HasPtr& rhs);
private:
	string* ps;
	int i;

public:
	HasPtr(const string& str = string()) : ps(new string(str)), i(0) {}
	HasPtr(const HasPtr& oth) : ps(oth.ps), i(oth.i) {}
	HasPtr(HasPtr&& oth) : ps(oth.ps), i(oth.i) { oth.ps = nullptr; } //配合移动构造,窃取资源;
	HasPtr& operator=(HasPtr oth) {
		swap(*this, oth);
		return *this;
	}
};

inline void swap(HasPtr& lhs, HasPtr& rhs) {
	using std::swap;
	swap(lhs.ps, rhs.ps);
	swap(lhs.i, rhs.i);
}
int _tmain()
{
	HasPtr ptr1("mao");
	HasPtr ptr2;

	ptr2 = std::move(ptr1); //调用移动构造;
<span style="white-space:pre">	</span>return(0);

}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值