- 1、智能指针使用
- 2、原理解析
#include#include // 需要引入头文件 using namespace std; int main(void) { // 不需要自己释放这个空间,他会自动释放,这就是基本使用 auto_ptr myptr(new int(10)); cout<<*myptr< 2、原理解析 B类中有一个A类型的指针,通过初始化B类,然后重载“* ->”操作符,实现,调用A类中的函数,并且B的析构函数会自动释放开辟的空间,不需要自己主动释放
#includeusing namespace std; class A { public: A(int a) { cout<<"A的构造函数"< m_a = a; } ~A() { cout<<"A的析构函数"< m_a< m_mpt = mypt; } A* operator->() { return this->m_mpt; } A& operator*() { return *m_mpt; } ~B() { if(this->m_mpt != NULL) { delete this->m_mpt; this->m_mpt = NULL; } } private: A* m_mpt; }; int main(void) { B myp(new A(100)); myp->fun(); (*myp).fun(); return 0; }



