本文学习自 狄泰软件学院 唐佐林老师的 C++课程
在C++工程项目中,尽量少的使用C中的原生指针,
用智能指针代替原生的指针变量
字符串我们用 string类来代替,避免使用字符指针
数组我们数组对象来代替
函数指针我们用函数对象来代替
实验1:内存泄漏
实验2:智能指针的创建,智能指针,通过对象模拟指针
实验1:内存泄漏
#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;
}
mhr@ubuntu:~/work/c++$
mhr@ubuntu:~/work/c++$ g++ 37-1.cpp
mhr@ubuntu:~/work/c++$ ./a.out
0
1
2
3
4
mhr@ubuntu:~/work/c++$
杜绝指针运算可以避免指针越界,避免野指针
如果上面的要求全部满足了,指针的比较就没有意义了
实验2:智能指针的创建,智能指针,通过对象模拟指针
包含:
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;
}
//拷贝构造,参数最后设置为空,因为需要 一片对空间最多只能由一个指针标识。转让管理权
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()
{
//通过类对象 模拟 指针行为,智能指针
/*
Test t; // 调用 Test()
Test t1(1); // 调用 Test(int v)
Test t2 = 2; // 调用 Test(int v)
int i(100);// ==> int i = 100;
*/
Pointer p1 = new Test(0);// Pointer p1(new Test(0));
cout << p1->value() << endl;
Pointer p2 = p1;
cout << p1.isNull() << endl;
cout << p2->value() << endl;
return 0;
}
mhr@ubuntu:~/work/c++$ g++ 37-2.cpp
mhr@ubuntu:~/work/c++$ ./a.out
Test(int i)
0
1
0
~Test()
mhr@ubuntu:~/work/c++$
注意 该智能指针所定义的类仅仅能够指像 Test固定的类型,暂时没有办法指向其他的类型,后期将修改智能指针类 可以指向任意的类。
只能堆空间 不可以是栈空间…