1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | #include <iostream> using namespace std; template <class object> class sian_ptr { public: object *m_object; // 构造函数接收外部传入的堆空间对象 sian_ptr(object *object) : m_object(object) {} // 当前对象被释放时,释放外部推空间内存 ~sian_ptr() { if (m_object == nullptr) return; delete m_object; } // 重载运算符->巧妙地将当前对象“指向”外部对象 object* operator->() { return m_object; } }; class Person { public: int m_age; Person() { cout << "Person()..." << endl; } ~Person() { cout << "~Person()..." << endl; } }; int main() { { // 模拟智能指针auto_ptr // auto_ptr<Person> p(new Person()); sian_ptr<Person> p(new Person()); p->m_age = 12; } system("pause"); return 0; } |
输出结果:
Person()…
~Person()…
请按任意键继续. . .