1 Star 0 Fork 0

非启鹏程/c++

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
智能指针改进.cpp 1.01 KB
一键复制 编辑 原始数据 按行查看 历史
template<class T>
class auto_ptr
{
public:
// RAII
auto_ptr(T* ptr = nullptr)
: _ptr(ptr)
, _isOwner(false)
{
if (_ptr)
_isOwner = true;
}
~auto_ptr()
{
if (_ptr && _isOwner)
{
delete _ptr;
_ptr = nullptr;
}
}
//////////////////////////////////
// 具有指针类似的行为
T& operator*()
{
return *_ptr;
}
T* operator->()
{
return _ptr;
}
///////////////////////////////////
// 解决浅拷贝的方式:资源管理权转移
// 资源管理:指对资源释放权利的转移
auto_ptr(const auto_ptr<T>& ap)
: _ptr(ap._ptr)
, _isOwner(ap._isOwner)
{
ap._isOwner = false;
}
auto_ptr<T>& operator=(const auto_ptr<T>& ap)
{
if (this != &ap)
{
if (_ptr && _isOwner)
delete _ptr;
_ptr = ap._ptr;
_isOwner = ap._isOwner;
ap._isOwner = false;
}
return *this;
}
private:
T* _ptr;
mutable bool _isOwner; // 资源真正的拥有者
};
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/dunqipeng/c1.git
git@gitee.com:dunqipeng/c1.git
dunqipeng
c1
c++
master

搜索帮助