#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