一篇文章带你搞定手写unique_ptr智能指针
相比于shared_ptr智能指针来说,unique_ptr智能指针较为简单,但是是面试场上常问的问题。属于应该掌握的知识点。
unique_ptr实现
#include <iostream>
using namespace std;
class Type
{
public:
int a = 1;
};
template<typename T>
class smart_ptr
{
public:
smart_ptr(T* ptr = NULL) : m_ptr(ptr) {}
~smart_ptr() {
delete m_ptr;
}
T& operator*() const { return *m_ptr; }
T* operator->() const { return m_ptr; }
operator bool() const { return m_ptr; }
// 搬移构造
smart_ptr(smart_ptr&& rhs) noexcept {
m_ptr = rhs.m_ptr;
rhs.m_ptr = NULL;
}
// 搬移赋值
smart_ptr& operator=(smart_ptr&& rhs) noexcept {
m_ptr = rhs.m_ptr;
rhs.m_ptr = NULL;
return *this;
}
private:
T* m_ptr;
};
int main()
{
smart_ptr<Type> sptr(new Type);
smart_ptr<Type> sptr2(std::move(sptr)); // 调用搬移构造
smart_ptr<Type> sptr3;
sptr3 = std::move(sptr2); // 调用搬移赋值
return 0;
} #面经#