共享指针
#include <iostream>
using namespace std;
template <class T>
class Share
{
public:
// 构造函数
Share(T* p= NULL) : key(p), size(new int(1)) {}
// 拷贝构造
Share(const Share& p) {
key = p.key;
size = p.size;
(*size)++;
}
// 移动构造
Share(Share&& p) {
key = p.key;
size = p.size;
p.key = NULL;
p.size = NULL;
}
// 移动赋值
Share& operator = (Share&& p) {
descrease();
key = p.key;
size = p.size;
p.key = NULL;
p.size = NULL;
return *this;
}
// 拷贝赋值
Share& operator = (const Share& p) {
descrease();
key = p.key;
size = p.size;
(*size)++;
return *this;
}
int use_count() {
return *size;
}
T* get() {
return key;
}
~Share() {
// 引用计数--,为0时释放内存
descrease();
}
private:
T* key;
int* size;
void descrease() {
if (size != NULL) {
if (--(*size) == 0) {
delete size;
if (key != NULL) {
delete key;
}
size = NULL;
key = NULL;
}
}
}
};
class Base
{
public:
Base() {
cout << "构造函数" << endl;
}
~Base() {
cout << "析构函数" << endl;
}
private:
};
int main()
{
Share<Base>i;
cout << i.get() << endl;
shared_ptr<Base>p(new Base);
cout << p.get() << " " << p.use_count() << endl;
shared_ptr<Base>q(p);
cout << p.get() << " " << p.use_count() << endl;
shared_ptr<Base>c(move(p));
cout << c.get() << " " << c.use_count() << endl;
cout << p.get() << " " << p.use_count() << endl;
cout << endl;
Share<Base>a(new Base);
cout << a.get() << " " << a.use_count() << endl;
Share<Base>b(a);
cout << b.get() << " " << b.use_count() << endl;
Share<Base>d(move(a));
cout << d.get() << " " << d.use_count() << endl;
cout << a.get() << " " << a.use_count() << endl;
}