gpt4 book ai didi

c++ - 智能指针模板和自动删除指针

转载 作者:行者123 更新时间:2023-11-28 01:46:17 24 4
gpt4 key购买 nike

我在一个网站上看到了这个简单的代码。我没有完全理解它。如果有人可以逐行分解代码并进行解释,那将对我很有帮助。

这是创建智能指针模板的代码(自动删除指针是创建此类指针的主要格言)

#include <iostream>    
using namespace std;

template <class T>
class SmartPtr {
T* ptr;

public:
explicit SmartPtr(T* p = NULL) {
ptr = p;
}
~SmartPtr() {
delete(ptr);
}
T& operator*() {
return *ptr;
}
T* operator->() {
return ptr;
}
};

int main() {
SmartPtr<int> ptr(new int());
*ptr = 20;

cout << *ptr;
return 0;
}

最佳答案

您的类 SmartPtr 封装了一个类型为 T 的指针,并重载了成员访问取消引用运算符 以允许访问封装的指针。此外,当它的析构函数被调用时,它释放了封装指针指向的分配内存。

你的类(class)有评论:

template <class T>
class SmartPtr {
T* ptr; // encapsulated pointer of type T

public:
// constructor for SmartPtr class which assigns the specified pointer to the
// encapsulated pointer
explicit SmartPtr(T* p = NULL) {
ptr = p;
}
// destructor for SmartPtr class which frees up the the allocated memory
// pointed by the encapsulated pointer
~SmartPtr() {
delete(ptr);
}
// overloads the dereference operator for SmartPtr class to allow syntax
// like: *instance = value;
T& operator*() {
return *ptr;
}
// overloads the member access operator for SmartPtr class to allow syntax
// like: instance->member();
T* operator->() {
return ptr;
}
};

SmartPtr 类的使用显示在您提供的main 函数中:

SmartPtr<int> ptr(new int());
*ptr = 20;

第一行执行 class template instantiation并通过使用 newly 调用构造函数来构造一个对象 (ptr)创建了 int 作为参数。

第二行调用重载的取消引用运算符并将值20 赋给封装的指针。这一行相当于:

ptr.operator*() = 20;

关于c++ - 智能指针模板和自动删除指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44967148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com