USB_Config_Vendor/CC_SDK/Include/TL/AutoDestruct.h
2026-02-03 14:36:30 +08:00

73 lines
1.9 KiB
C++

#ifndef SDK_TL_AUTODESTRUCT_H
#define SDK_TL_AUTODESTRUCT_H
#include "iostream"
namespace CTL{
template<typename T>
class AutoDestruct{
public:
//--------------------------------------------------------------------------------------------------------------
AutoDestruct(T* ptr){
if(ptr){
m_ptr = std::move(ptr);
}
}
AutoDestruct(AutoDestruct&& other) noexcept {
this->m_ptr = other.m_ptr;
other.m_ptr = nullptr;
}
~AutoDestruct(){
if (m_ptr && m_is_owner) {
delete m_ptr;
}
m_ptr = nullptr;
}
//--------------------------------------------------------------------------------------------------------------
T* Get(){
return m_ptr;
}
const T* Get() const{
return m_ptr;
}
T* get(){
return m_ptr;
}
const T* get() const{
return m_ptr;
}
explicit operator bool() const {
return m_ptr != nullptr;
}
T& operator*() const {
return *m_ptr; // 假设 ptr 是内部 Term*
}
T* operator->() const {
return m_ptr; // 假设 ptr 是内部 Term*
}
AutoDestruct& operator=(T* ptr){
delete m_ptr;
m_ptr = ptr;
return *this;
}
AutoDestruct& operator=(AutoDestruct&& rhs) noexcept {
m_ptr = rhs.m_ptr;
rhs.m_ptr = nullptr;
return *this;
}
void reset(T* ptr = nullptr){
delete m_ptr;
m_ptr = ptr;
}
void release() {
m_is_owner = false;
}
//--------------------------------------------------------------------------------------------------------------
private:
T* m_ptr = nullptr;
bool m_is_owner = true;
};
}
#endif