小编Ala*_*ner的帖子

这是一个聪明的指针吗?

请看下面的代码.这是一个聪明的指针吗?如果是这样,为什么第一个对象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> …
Run Code Online (Sandbox Code Playgroud)

c++

2
推荐指数
1
解决办法
72
查看次数

标签 统计

c++ ×1