关于指针:c+内存泄漏与智能指针
您好,看到文章的您,如果您是c++初学者,这部分内容须要学习好数据结构中指针和栈的内容,否则可能会有肯定难度,只做理解即可什么是内存透露什么是内存透露,简略来说,就是 1.动静申请堆空间,用完后不偿还2。C++ 语言中没有垃圾回收的机制3.指针无法控制所指堆空间的生命周期例如上面的例子: #include<iostream>#include<string.h>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;}智能指针的利用从输入后果能够看出,指针被用于了大小比拟和运算,这显然不是咱们冀望的。于是有了智能指针,demo如下: #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) { 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;}这里次要解决的以下问题 ...