-
内存泄露(臭名昭著的BUG)
-
动态申请堆空间,用完后不归还
-
C++语言中没有垃圾回收机制
-
指针无法控制所指堆空间的生命周期
-
我们需要什么?
-
需要一个特殊的指针
-
指针生命周期结束时主动释放堆空间
-
一片堆空间最多只能由一个指针标识
-
杜绝指针运算和指针比较(可以避免野指针)
-
解决方法
-
指针操作符(->和*)
-
只能通过类的成员函数重载
-
重载函数不能使用参数
-
只能定义一个重载函数
-
小结:
-
指针操作符(->和*)可以被重载
-
重载操作符能够使用对象代替指针
-
智能指针只能用于指向堆空间的内存
-
智能指针的意义在于最大程度的避免内存问题
智能指针使用军规:只能用来指向堆空间中的对象或者变量
#include <iostream>
#include <string>
using namespace std;
class Test
{
int i;
public:
Test(int _val)
{
this->i = _val;
cout << "Test(int _val)" << endl;
}
~Test()
{
cout << "~Test()" << endl;
}
int get_value()
{
return i;
}
};
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;
}
~Pointer()
{
delete mp;
}
//如果mp等于NULL,返回true:1
bool isNULL()
{
return (mp==NULL);
}
};
int main()
{
cout << "Hello World!\n" <<endl;
//使用类对象来代替指针,在变量p(对象)生命周期结束时
//执行析构函数,释放变量mp
Pointer p = new Test(6);
cout << p->get_value() << endl;
Pointer p1 = p;
cout << p.isNULL() << endl;
cout << p1->get_value() << endl;
}
运行结果:
Hello World!
Test(int _val)
6
1
6
~Test()
来源:https://www.cnblogs.com/chengeputongren/p/12234826.html