实现share_ptr智能指针
c++
class A{
public:
int age;
std::string name;
A(int i){
name = "Tim";
age = i;
std::cout << "对象A"<<age<<"被创建\n";
}
~A(){
std::cout << "对象A"<<age<<"被析构\n";
}
};
template<class T>
class MySharePtr{
public:
MySharePtr(T* type = nullptr){
std::cout<<"智能指针创建 \n";
ptr_ = type;
if(type == nullptr){
count_ = new size_t(0);
}else{
count_ = new size_t(1);
}
}
MySharePtr(const MySharePtr& temp_ptr){
ptr_ = temp_ptr.ptr_;
count_ = temp_ptr.count_;
(*count_)++;
std::cout<<"拷贝构造已经调用 \n";
}
~MySharePtr(){
if(ptr_ == nullptr){
delete count_;
return;
}
(*count_)--;
if((*count_) == 0){
delete ptr_;
delete count_;
std::cout<<"智能指针释放 \n";
}
}
T* operator->(){
assert(ptr_ != nullptr);
return ptr_;
}
T& operator*(){
assert(ptr_ != nullptr);
return *ptr_;
}
size_t use_count(){
return *count_;
}
MySharePtr& operator=(MySharePtr& temp_ptr){
std::cout<<"赋值构造函数调用"<<"\n";
(*count_)--;
if((*count_) == 0){
delete count_;
delete ptr_;
}
(*count_)++;
ptr_ = temp_ptr.ptr_;
count_ = temp_ptr.count_;
return *this;
}
private:
T* ptr_;
size_t* count_;
};
template <class T, typename... Args>
MySharePtr<T> My_make_shared(Args&&... args) {
// 使用 new 运算符为类型 T 分配内存并构造对象
T* ptr = new T(std::forward<Args>(args)...);
// 创建 MySharePtr 对象并返回
return MySharePtr<T>(ptr);
}c++
int main()
{
std::cout<<"\n";
MySharePtr<A> ptr = My_make_shared<A>(88);
// MySharePtr<A> ptr = new A(88);
std::cout<<ptr->age<<"\n";
std::cout<<(*ptr).age<<"\n";
MySharePtr<A> ptr2(new A(2));
ptr2 = ptr;//调用赋值重载
MySharePtr<A> ptr3 = ptr2;//隐式构造 调用拷贝构造
MySharePtr<A> ptr4(ptr3);//显式构造 调用拷贝构造
std::cout<<ptr3.use_count()<<ptr2.use_count()<<ptr4.use_count()<<"\n";
auto func = [](int a){
std::cout<<a<<"\n";
};
return 0;
}