scope

xiaoxiao2021-02-28  94

#include <iostream> #include <cassert> using namespace std; template <typename T> class scoped_ptr { public: typedef T elememnt_type; explicit scoped_ptr(T* p = 0) :px(p){ cout << "scoped_ptr construct" << endl; }; ~scoped_ptr(){ cout << "scoped_ptr deconstruct" << endl; delete px; } T& operator*()const { assert(px != 0); return *px; } T* operator->()const { assert(px != 0); return px; } T* get()const { return px; } void swap(scoped_ptr& p) { T* temp = p.px; p.px = px; px = temp; } void reset(T* p = 0){ assert(p == 0 || p != px); scoped_ptr<T>(p).swap(*this);//这句话很吊 //用临时对象交换指针,把p给了this对象,临时对象消亡delete this; } operator bool() { cout << "scoped_ptr operator bool()" << endl; return px != 0; } bool operator!() { cout << "scoped_ptr bool operator!()" << endl; return px == 0; } private: T* px; scoped_ptr(const scoped_ptr& ptr); scoped_ptr& operator=(const scoped_ptr& ptr); bool operator==(const scoped_ptr& ptr); bool operator!=(const scoped_ptr& ptr); }; int main(){ scoped_ptr<int> p(new int(10));//scoped_ptr construct if (p) { cout << "p true" << endl;//p true } else { cout << "p false"<<endl; } scoped_ptr<int> p2(new int(20)); p2.swap(p); cout << *p << ends << *p2 << endl;//20 10 p2.reset(new int(100));//scoped_ptr construct scoped_ptr deconstruct cout << *p << ends << *p2 << endl;//20 100 return 0; }

转载请注明原文地址: https://www.6miu.com/read-42652.html

最新回复(0)