|
一、智能指针的学习: 1、内存泄漏: 关于内存泄漏这个问题,一般都会牵扯到指针这个话题,也就是我们常说的动态内存分配;然而在程序员手动进行堆空间的分配时(指针无法控制所指堆空间的生命周期,),往往在写完程序的时候,程序员一不小心就忘了释放已经手动分配的内存大小,导致软件Bug不断(也就是内存泄漏)。 在C++语言里面又没有垃圾回收的机制(不像高级语言Java有自动的垃圾回收机制,),所以程序员在写程序的时候,经常会发生刚才上面说的那种情况,这里我们来看一个例子: #include <iostream>#include <string> using namespace std; class Test { int i; public: Test(int i) { this->i = i; } int value() { return i; } ~Test() { } }; int main() { for(int i=0; i<5; i++) { Test* p = new Test(i); cout << p->value() << endl; } return 0; } 输出结果: txp@ubuntu:~$ ./a.out0 1 2 3 4 注解:上面分配的堆空间,没有释放掉 2、我们需要什么?
3、智能指针的使用:
代码实践: #include <iostream>#include <string> using namespace std; class Test { int i; public: Test(int i) { cout << "Test(int i)" << endl; this->i = i; } int value() { return i; } ~Test() { cout << "~Test()" << endl; } }; class Pointer { Test* mp; public: Pointer(Test* p = NULL)// 1,智能指针对象,通过类的普通构造函数完成; { mp = p; } Pointer(const Pointer& obj)//避免多次释放内存,通过拷贝构造函数和赋值操作符完成; { mp = obj.mp;// 传递堆空间的控制; const_cast<Pointer&>(obj).mp = NULL;//初始化对象不管之前的;堆空间了,做所有权的转移,保证堆空间最多只能由一个对象被标识; } Pointer& operator = (const Pointer& obj) { if( this != &obj ) { delete mp; mp = obj.mp; const_cast<Pointer&>(obj).mp = NULL; } return *this; } Test* operator -> () // 返回指针,准备指示; { return mp; } Test& operator * () // 解引用,返回对象; { return *mp; } bool isNull() { return (mp == NULL); } ~Pointer() { delete mp; } }; int main() { Pointer p1 = new Test(0); cout << p1->value() << endl; Pointer p2 = p1; cout << p1.isNull() << endl; cout << p2->value() << endl; return 0; } 输出结果: txp@ubuntu:~$ ./a.outTest(int i) 0 1 0 ~Test() 总结提示:智能指针是一个类,这个类的构造函数中传入一个普通指针,析构函数中释放传入的指针。智能指针的类都是栈上的对象,所以当函数(或程序)结束时会自动被释放 二、总结:
好了,今天的分享就到这里,如果文章中有错误或者不理解的地方,可以交流互动,一起进步。 |
微信公众号
手机版