C++ 实现智能指针my_auto_ptr支持指针剥离及函数间传递
摘要:
本文提出了一种自定义智能指针类my_auto_ptr,解决了标准智能指针在指针剥离和传递方面的局限性。该实现利用shared_ptr管理指针地址而非直接管理对象,既保留了指针的可传递性(通过共享地址计数),又提供了类似auto_ptr的release()功能。核心特点是:1) 通过共享指针存储指针地址而非对象本身;2) 最后一个持有者自动释放内存;3) 支持指针剥离和重置操作。这种设计在需要跨函数或信号槽传递指针时特别有用,弥补了unique_ptr不可复制和shared_ptr无法释放所有权的不足。
C++标准中的auto_ptr在C++11以后已经不建议使用了,在C++17中已经移除,规范中推荐使用 unique_ptr、shared_ptr 和 weak_ptr 。
但是在实际使用过程中,想从shared_ptr中将指针剥离出来,在其他地方管理,由于shared_ptr没有release方法,无法实现。
unique_ptr中有release方法,但是想在函数间或Qt信号槽间传递,由于unique_ptr的独占性,不允许复制传递,无法实现。
现利用shared_ptr只将指针的地址管理起来,便于指针剥离,也不影响函数间传递:
template <class _Ty>
class my_auto_ptr
{
public:my_auto_ptr(): m_ptrInt(std::make_shared<qint64>(0)){}my_auto_ptr(_Ty* ptr): m_ptrInt(std::make_shared<qint64>((qint64)ptr)){}~my_auto_ptr(){if (m_ptrInt.use_count() == 1){auto temp = get();if (temp){delete temp;temp = nullptr;}}}_Ty* operator->() const noexcept{return get();}_Ty* get() const noexcept{auto ptr = reinterpret_cast<_Ty*>(*m_ptrInt);return ptr;}_Ty* release(){auto temp = get();*m_ptrInt = 0;return temp;}void reset(_Ty* _Px){ my_auto_ptr(_Px).swap(*this);}void swap(my_auto_ptr& _Other) noexcept{m_ptrInt.swap(_Other.m_ptrInt);}private:std::shared_ptr<qint64> m_ptrInt;
};
