智能指针模板和自动删除指针

template for a smartpointer and auto deletion of the pointer

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

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

#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;
}

"Break down line by line"有点过分,以后有不懂的地方尽量单独提一下。但是因为没有那么多代码...

#include <iostream>
using namespace std;
template <class T> //make it a template in order to be able to store any type
class SmartPtr {
T *ptr; //wrapped pointer
public: explicit SmartPtr(T *p = NULL) { ptr = p; } //basic constructor

//delete pointer when the object dies.
//Note that this means that this is meant to be a unique pointer, 
//a shared pointer would have to count occurencies first
 ~SmartPtr() { delete(ptr); } 

//dereference operator to manipulate the content. 
//I prefer to go with T& instead of T & to make it clear that it is
//"reference of type T"
T & operator * () {  return *ptr; }
//bad operator which exposes the pointer itself.
//Make this const, like const T* operator -> () const { ... }
//else this could be used for the constructor again,
//leading to undefined behaviour when the pointer is deleted twice
T * operator -> () { return ptr; } }; //class ending brace at bad position

int main(){
SmartPtr<int> ptr(new int());
*ptr = 20;
cout << *ptr;
return 0; }

您的 class 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 class 的用法显示在您提供的 main 函数中:

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

第一行执行 class template instantiation and constructs an object (ptr) by calling the contructor with newly 创建的 int 作为参数。

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

ptr.operator*() = 20;