smartpointer的模板和指针的自动删除

时间:2017-07-07 09:22:08

标签: 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;
}

2 个答案:

答案 0 :(得分:1)

&#34;逐行分解&#34;有点过分,对于未来,尽量提一下你不了解的单个部分。但是因为代码不是那么多......

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

答案 1 :(得分:1)

您的班级SmartPtr封装了T类型的指针,并重载成员访问取消引用运算符以允许访问封装指针。此外,它可以在调用其析构函数时释放封装指针所指向的已分配内存。

你的班级有赞:

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;