C++ Primer 行为像值的类与行为像指针的类Hasptr

 

#ifndef HASPTR
#define HASPTR
#include<iostream>
#include<string>
class HasPtr   //行为像值的类
{
	friend void swap(HasPtr &hp1, HasPtr &hp2);
	friend bool operator<(const HasPtr &hp, const HasPtr &hp2);
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) {}
	std::string get() const{ return *ps; }
	void set(const std::string &s) { *ps = s; }
	HasPtr& operator=(const HasPtr &hp);  //注意到拷贝赋值运算符和拷贝构造函数都是使ps指向一个拷贝的new string 
		                             //因为如果直接把所指对象赋给ps 那么就是让ps也指向该对象 就是指向同一对象而非拷贝相同的值了
	~HasPtr() { delete ps; };   //函数体一般为空,但是ps为内置指针,若不delte,折构并不会释放其所指内存
private:
	std::string *ps;
	int i;
};
HasPtr& HasPtr::operator=(const HasPtr &hp)  
{
	//ps = new std::string(*hp.ps);   //这样写不严谨,若原本指针有所指向,这样写就无法再释放原来所指的内存了
	//i = hp.i;
	//return *this;       //正确写法如下:
	auto newptr = new std::string(*hp.ps);
	delete ps;   //释放原来所指的内存,现在ps为空悬指针
	ps = newptr;   //将ps指向新区域
	i = hp.i;
	return *this;
}
bool operator<(const HasPtr &hp,const HasPtr &hp2)
{
	return *hp.ps < *hp2.ps;
}
inline void swap(HasPtr &hp1, HasPtr &hp2)
{
	/*std::swap(hp1.ps, hp2.ps);   //这个例子可以这样写,但一般情况下,想调用自定义的swap不这么写
	std::swap(hp1.i, hp2.i);*/
	//一般写法
	using std::swap;
	swap(hp1.ps, hp2.ps);   //这样写的话若有自定义则会调用自定义,若无则会调用标准库的swap
	swap(hp1.i, hp2.i);
	std::cout << "call swap(HasPtr &hp1,HasPtr &hp2)" << std::endl;
}
//class HasPtr   //行为像指针的类
//{
//public:
//	HasPtr(const std::string & s = std::string()) :
//		ps(new std::string(s)), i(0), use(new size_t(1)) {}
//	HasPtr(const HasPtr &hp) :ps(hp.ps), i(hp.i), use(hp.use) { ++*use; }
//	HasPtr& operator=(const HasPtr&);
//	~HasPtr();
//private:
//	std::string *ps; 
//	int i;
//	size_t *use;
//};
//HasPtr::~HasPtr()
//{
//	if (--*use == 0)
//	{
//		delete ps;
//		delete use;
//	}
//}
//HasPtr& HasPtr::operator=(const HasPtr &hp)
//{
//	++*hp.use;
//	if (--*use == 0)
//	{
//		delete ps;
//		delete use;
//	}
//	ps = hp.ps;
//	i = hp.i;
//	use = hp.use;
//	return *this;
//}
#endif // !HASPTR

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值