c++实现一个unique_ptr声明和定义分开
时间: 2023-12-27 11:04:43 浏览: 34
unique_ptr的声明和定义可以分开实现,如下所示:
声明:
template <typename T>
class unique_ptr {
public:
unique_ptr();
unique_ptr(T* ptr);
unique_ptr(unique_ptr&& other);
~unique_ptr();
T* operator->() const;
T& operator*() const;
operator bool() const;
unique_ptr& operator=(unique_ptr&& other);
T* get() const;
void reset(T* ptr = nullptr);
void swap(unique_ptr& other);
unique_ptr(const unique_ptr&) = delete;
unique_ptr& operator=(const unique_ptr&) = delete;
private:
T* m_ptr;
};
定义:
template <typename T>
unique_ptr<T>::unique_ptr() : m_ptr(nullptr) {}
template <typename T>
unique_ptr<T>::unique_ptr(T* ptr) : m_ptr(ptr) {}
template <typename T>
unique_ptr<T>::unique_ptr(unique_ptr&& other) : m_ptr(other.m_ptr) {
other.m_ptr = nullptr;
}
template <typename T>
unique_ptr<T>::~unique_ptr() {
delete m_ptr;
}
template <typename T>
T* unique_ptr<T>::operator->() const {
return m_ptr;
}
template <typename T>
T& unique_ptr<T>::operator*() const {
return *m_ptr;
}
template <typename T>
unique_ptr<T>::operator bool() const {
return m_ptr != nullptr;
}
template <typename T>
unique_ptr<T>& unique_ptr<T>::operator=(unique_ptr&& other) {
if (this != &other) {
delete m_ptr;
m_ptr = other.m_ptr;
other.m_ptr = nullptr;
}
return *this;
}
template <typename T>
T* unique_ptr<T>::get() const {
return m_ptr;
}
template <typename T>
void unique_ptr<T>::reset(T* ptr) {
delete m_ptr;
m_ptr = ptr;
}
template <typename T>
void unique_ptr<T>::swap(unique_ptr& other) {
std::swap(m_ptr, other.m_ptr);
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)