这是一个聪明的指针

Is this a smart pointer?

本文关键字:指针 一个      更新时间:2023-10-16

请看下面的代码。这是一个聪明的指针吗?如果是这样,为什么第一个对象 p1 在代码末尾悬空?(也就是说 p2 被析构函数删除,但 p1 仍然存在,为什么?

#include <iostream>
#include <vector>
using namespace std;
template <class T> class my_auto_ptr {
    T* myptr;
public:
    my_auto_ptr(T* ptr = 0) : myptr(ptr) { }
    ~my_auto_ptr() {
        delete myptr;
    }
    T* operator ->() const {
        if (myptr != nullptr)  return myptr;
        else throw runtime_error("");
    }
    T& operator* () const {
        if (myptr != nullptr)  return *myptr;
        else throw runtime_error("");
    }
    T* release() {
        T* rptr = myptr;
        myptr = 0;
        return rptr;
    }
};
//----------------------------------
int main() try {
    my_auto_ptr<vector<int> > p1(new vector<int>(4, 5));
    cout << p1->size() << endl;
    my_auto_ptr<int> p2(new int(6));
    cout << *p2 << endl;
    return 0;
}
//-------------------------------
catch (...) {
    cerr << "Exception occurred.n";
    return 1;
}

这是一个聪明的指针吗?

不。它是可复制和可分配的,但执行其中任一操作都会导致多次删除。您需要确保它是不可复制和不可分配的,或者它实现了 3 或 5 的规则。