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

标签 c++ templates pointers smart-pointers

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

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

#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/

相关文章:

c++ - boost 日期/时间

Perl - 模板工具包 - 如何获取模板中的变量列表?

c - 链表插入节点什么都不显示

c - 在 C 中,普通数组和使用 malloc 创建的数组有什么区别?

c++ - 为什么 clang 处理这个简单的 std::variant 代码的异常?

c++ - 为什么 valgrind 将 64 位程序中的指针大小报告为 4 个字节

javascript - 带过渡的动态 knockout 模板

c - 使用指针在 C 中复制字符串不显示预期结果

c++ - C++中如何根据参数的值返回不同的类型?

c++ - 带模板的函数指针