c++智能指针 示例讲解
【摘要】
智能指针实际上就是通过模板技术实现的一个类
内存泄露(臭名昭著的Bug)——在软件开发和测试阶段都不容易被发现 -动态申请堆空间,用完后不归还 -C++语言中没有垃圾回收的机制 -指针无法控制所指堆空间的生命周期
当代C++软件平台中的智能指针 -指针生命周期结束时主动释放堆空间 -一片堆空间最多只能由一个指针标识
-杜绝指针运算和指针比较
智能指针的...
智能指针实际上就是通过模板技术实现的一个类
内存泄露(臭名昭著的Bug)——在软件开发和测试阶段都不容易被发现
-动态申请堆空间,用完后不归还
-C++语言中没有垃圾回收的机制
-指针无法控制所指堆空间的生命周期
当代C++软件平台中的智能指针
-指针生命周期结束时主动释放堆空间
-一片堆空间最多只能由一个指针标识
-杜绝指针运算和指针比较
智能指针的设计方案
-通过类模板描述指针的行为
能够定义不同类型的指针对象
-重载指针特征操作符(->和*)
利用对象模拟原生指针的行为
SmartPointer.h
-
#ifndef SMARTPOINTER_H_
-
#define SMARTPOINTER_H_
-
-
namespace DTLib
-
{
-
template <typename T>
-
class SmartPointer
-
{
-
protected:
-
T* m_pointer;
-
public:
-
SmartPointer(T* p =NULL)
-
{
-
m_pointer = p;
-
}
-
-
T* operator ->()
-
{
-
return m_pointer;
-
}
-
-
T& operator *()
-
{
-
return *m_pointer;
-
}
-
-
SmartPointer(const SmartPointer<T>& obj)
-
{
-
m_pointer = obj.m_pointer;
-
const_cast<SmartPointer<T> &>(obj).m_pointer = NULL;
-
}
-
-
SmartPointer<T>& operator = (const SmartPointer<T>& obj)
-
{
-
if(this != &obj)
-
{
-
delete m_pointer;
-
m_pointer = obj.m_pointer;
-
const_cast<SmartPointer<T> &>(obj).m_pointer = NULL;
-
}
-
-
return *this; //可以支持连续赋值
-
}
-
-
T* get()
-
{
-
return m_pointer;
-
}
-
-
bool isNull()
-
{
-
return (m_pointer == NULL);
-
}
-
-
~SmartPointer()
-
{
-
delete m_pointer;
-
}
-
-
};
-
-
}
-
-
#endif // SMARTPOINTER_H_
main.cpp
-
#include <iostream>
-
#include "SmartPointer.h"
-
-
using namespace std;
-
using namespace DTLib;
-
-
class Test
-
{
-
public:
-
Test()
-
{
-
cout << "Test()" << endl;
-
}
-
~Test()
-
{
-
cout << "~Test()" << endl;
-
}
-
-
-
};
-
-
int main()
-
{
-
-
SmartPointer<Test> sp = new Test();
-
SmartPointer<Test> nsp;
-
-
nsp = sp;
-
cout << sp.isNull() << endl;
-
cout << nsp.isNull() << endl;
-
-
cout << "sp = " << sp.get() << endl;
-
cout << "nsp = " << nsp.get() << endl;
-
-
-
return 0;
-
}
文章来源: blog.csdn.net,作者:网奇,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/jacke121/article/details/116955666
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)