auto_ptr
- auto_ptr这个智能指针在c++11中已经被遗弃,原因如下:在拷贝与赋值操作时,智能指针所管理的对象会发生拥有权转移,如果这个时候程序员去使用已经被转移拥有权的智能指针,不会发生编译错误,却在访问管理的对象时导致程序运行出错。这是一种很危险的行为。因此在c++11中引入了unique_ptr,参见下篇。
- 示例如下:
#include <iostream>
#include <memory>
using namespace std;
int main() {
auto_ptr<int> ptr1(new int(100));
auto_ptr<int> ptr2(ptr1);
cout << *ptr1.get() << endl;
return 0;
}
- auto_ptr源码如下:
#include <cassert>
template<typename _Tp1>
struct auto_ptr_ref
{
_Tp1* _M_ptr;
explicit auto_ptr_ref(_Tp1* __p) : _M_ptr(__p) { }
};
template<typename _Tp>
class auto_ptr
{
private:
_Tp* _M_ptr;
public:
typedef _Tp element_type;
explicit auto_ptr(element_type* __p = 0) throw() : _M_ptr(__p) { }
auto_ptr(auto_ptr& __a) throw() : _M_ptr(__a.release()) { }
template<typename _Tp1>
auto_ptr(auto_ptr<_Tp1>& __a) throw() : _M_ptr(__a.release()) { }
auto_ptr& operator=(auto_ptr& __a) throw()
{
reset(__a.release());
return *this;
}
template<typename _Tp1>
auto_ptr& operator=(auto_ptr<_Tp1>& __a) throw()
{
reset(__a.release());
return *this;
}
~auto_ptr() { if (_M_ptr) delete _M_ptr; }
element_type& operator*() const throw()
{
assert(_M_ptr != nullptr);
return *_M_ptr;
}
element_type* operator->() const throw()
{
assert(_M_ptr != nullptr);
return _M_ptr;
}
element_type* get() const throw() { return _M_ptr; }
element_type* release() throw()
{
element_type* __tmp = _M_ptr;
_M_ptr = nullptr;
return __tmp;
}
void reset(element_type* __p = 0) throw()
{
if (__p != _M_ptr)
{
delete _M_ptr;
_M_ptr = __p;
}
}
auto_ptr(auto_ptr_ref<element_type> __ref) throw()
: _M_ptr(__ref._M_ptr) { }
auto_ptr& operator=(auto_ptr_ref<element_type> __ref) throw()
{
if (__ref._M_ptr != this->get())
{
delete _M_ptr;
_M_ptr = __ref._M_ptr;
}
return *this;
}
template<typename _Tp1>
operator auto_ptr_ref<_Tp1>() throw()
{
return auto_ptr_ref<_Tp1>(this->release());
}
template<typename _Tp1>
operator auto_ptr<_Tp1>() throw()
{
return auto_ptr<_Tp1>(this->release());
}
};
template<>
class auto_ptr<void>
{
public:
typedef void element_type;
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)