#include <bits/stdc++.h>
using namespace std;
template <class T>
class Test {
public:
Test(int test):test_(test){
cout <<"Test构造"<< endl;
}
void Out(T i);
~Test() {
cout <<"Test析构"<< endl;
}
int test_;
};
template<class T>
void Test<T>::Out(T i) {
cout <<test_<<endl;
cout <<i<<endl;
}
template <class T>
class Shared_Ptr {
public:
Shared_Ptr(T* ptr) {
count_ = new int(1);
ptr_ = ptr;
}
Shared_Ptr& operator=(Shared_Ptr& sptr) {
if(sptr.ptr_ == this->ptr_) {
return *this;
}else {
if(*this->count_ == 1) {
*this->count_--;
delete this->ptr_;
++*sptr.count_;
this->ptr_ = sptr.ptr_;
this->count_ = sptr.count_;
}else{
*this->count_--;
++*sptr.count_;
this->ptr_ = sptr.ptr_;
this->count_ = sptr.count_;
}
}
cout <<"引用计数 = "<<*this->count_<< endl;
}
~ Shared_Ptr() {
if(*count_ == 1) {
*count_--;
cout <<"释放资源"<< endl;
delete ptr_;
}else {
cout <<"引用计数--"<< endl;
*count_--;
}
}
private:
int* count_ = nullptr;
T* ptr_;
};
int main() {
Test<int> t(1);
t.Out(1);
return 0;
}
- 思想就是利用一个引用计数指针,一个指向管理对象的指针,然后重载operator=运算符。
- 需要注意的就是:类模板在外部使用上需要明确类型,类模板的模板函数在外部定义时也是需要明确类型,但是在声明class的时候不需要明确类型。