#include <iostream>
#include <memory> // 需要包含这个头文件
int main()
{
std::shared_ptr<int> p1 = std::make_shared<int>();
*p1 = 78;
std::cout << "p1 = " << *p1 << std::endl; // 输出78
return 0;
}
智能指针类包含两个成员变量:引用计数指针,管理对象的指针
当引用计数为0时,释放内存,否则不处理
重载和使用相关的所有操作符等,比如赋值运算符会将引用计数+1
重载*操作符,可获得管理对象的指针
可参考实现的demo
#include<bits/stdc++.h>
using namespace std;
template <typename MyStruct>
class SharedPtr {
public:
SharedPtr(MyStruct* a)
: a_(a) {
cout << "SharedPtr()" << endl;
b_ = new atomic<int>(1);
}
~SharedPtr() {
cout << "~SharedPtr()" << endl;
if (!(--*b_)) {
cout << "delete real ptr" << endl;
ToStirng();
delete a_;
a_ = NULL;
delete b_;
b_ = NULL;
}
}
SharedPtr<MyStruct>& operator =(const SharedPtr<MyStruct>& another) {
cout << "operator =" << endl;
if (this != &another) {
if (this->a_) {
if (!(--*this->b_)) {
cout << "delete real ptr" << endl;
ToStirng();
delete this->a_;
this->a_ = NULL;
delete this->b_;
this->b_ = NULL;
}
}
if (another.a_) {
this->a_ = another.a_;
this->b_ = another.b_;
*this->b_ ++ ;
}
}
return *this;
}
MyStruct operator *() {
cout << "operator *" << endl;
return *a_;
}
private:
void ToStirng() {
cout << *a_ << endl;
}
MyStruct* a_;
atomic<int>* b_;
};
int main() {
string* my_struct = new string("str1");
SharedPtr<string> a(my_struct);
string* my_struct2 = new string("str2");
SharedPtr<string> b(my_struct2);
b = a;
cout << *b << endl;
return 0;
}
struct EnableSharedPtr : enable_shared_from_this<EnableSharedPtr> {
public:
shared_ptr<EnableSharedPtr> getptr() {
return shared_from_this();
}
~EnableSharedPtr() {
cout << "~EnableSharedPtr() called" << endl;
}
};
int main()
{
shared_ptr<EnableSharedPtr> gp1(new EnableSharedPtr());
// 注意不能使用raw 指针
// EnableSharedPtr* gp1 = new EnableSharedPtr();
shared_ptr<EnableSharedPtr> gp2 = gp1->getptr();
cout << "gp1.use_count() = " << gp1.use_count() << endl;
cout << "gp2.use_count() = " << gp2.use_count() << endl;
return 0;
}
boost精简代码如下
class enable_shared_from_this
{
shared_ptr<const _Tp> shared_from_this() const
{
return shared_ptr<const _Tp>(this->_M_weak_this);
}
mutable weak_ptr<_Tp> _M_weak_this;
};
可理解为enable_shared_from_this
所有与该对象相关的操作都与该引用计数指针相关
因为类内部,如果不包含引用计数指针,不能直接生成shared_ptr
原文:https://www.cnblogs.com/jamgun/p/14645149.html