C++ 智能指针简单解析
-
本文通过代码的形式来探讨各类指针的区别
首先是类的声明,用于测试用
class People { public: void doWalk(){ cout << "走路" << endl; }; };
常规new指针
-
定义一个使用new指针的常规方法
//使用常规new指针 bool useNormalPtr() { People * p_People = new People(); p_People->doWalk(); People* p_MPeople = p_People; cout << "转移auto_ptr指针" << endl; p_MPeople->doWalk(); p_People->doWalk(); cout << "p_People地址" << endl; cout << p_People << endl; cout << "p_MPeople地址" << endl; cout << p_MPeople << endl; delete p_MPeople; return true; }代码比较简单,运行结果:
- 得出结论:
- new出来的指针,必须自己delete 不然转移的情况,无法导致内存地址的释放。
Auto_ptr指针
- 定义一个使用auto_ptr指针的方法
//使用auto_ptr
bool useAutoPtr()
{
std::auto_ptr<People> p_People(new People());
p_People->doWalk();
std::auto_ptr<People> p_MPeople = p_People;
cout << "转移auto_ptr指针" << endl;
p_MPeople->doWalk();
p_People->doWalk();
return true;
}
运行结果:
- 得出结论:
-
- 智能指针转移过程 会直接释放原先的内存地址,起到了自动释放内存的效果。
···· 未完待续