shared_ptr
- 两个成员:引用计数与指针
- 成员函数:构造函数、拷贝构造函数、拷贝赋值操作符、析构函数、解引用操作符重载、指向对象操作符重载
#pragma once
#include <iostream>
using namespace std;
template <typename T>
class Shared_ptr{
public:
Shared_ptr(T *p):ptr(p),pn(new long(1)){}
Shared_ptr(const Shared_ptr& rhs) : pn(&(++*rhs.pn)),ptr(rhs.ptr){}
Shared_ptr& operator=(const Shared_ptr& rhs){
Shared_ptr temp = rhs;
if( this->ptr == nullptr && --*this->pn == 0 )
{
delete ptr;
delete pn;
}
ptr = temp.ptr;
pn = temp.pn;
return *this;
}
~Shared_ptr()
{
if(--*pn == 0)
{
delete ptr;
delete pn;
}
}
int getref()
{
return *pn;
}
T& operator*()
{
return *ptr;
}
T* operator->()
{
return ptr;
}
private:
T* ptr;
long* pn;
};
```cpp
#include <iostream>
#include "My_shared_ptr.hpp"
using namespace std;
struct a
{
void print()
{
cout << "out" << endl;
}
};
int main()
{
My_shared_ptr<a>A = new a;
A->print();
return 0;
}
function-like classes(仿函数)
class a
{
bool operator()(bool a)const
{
return a;
}
};