内存泄露
动态申请堆空间,用完后不归还
C++语言中没有垃圾回收机制
指针无法控制所指堆空间的生命周期
例:内存泄露
#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;
}
输出:
0
1
2
3
4
深度的思考:
需要一个特殊的指针
指针的生命周期结束时主动释放堆空间
一片堆空间最多只能由一个指针标识
杜绝指针运算和指针比较
例:
智能指针:
#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;
}
Test* operator -> ()
{
return mp;
}
Test& operator * ()
{
return *mp;
}
bool isNull()
{
return (mp == NULL);
}
~Pointer()
{
delete mp;
}
};
int main()
{
for(int i=0; i<5; i++)
{
Pointer p1 = new Test(i);
cout << p1->value() << endl;
}
return 0;
}
输出结果:
Test(int i)
0
~Test()
Test(int i)
1
~Test()
Test(int i)
2
~Test()
Test(int i)
3
~Test()
Test(int i)
4
~Test()
例:智能指针
#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;
}
输出:
Test(int i)
0
1
0
~Test()
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。