[glacier] Add UniquePtr and Move

This commit is contained in:
Drew Galbraith 2023-06-26 11:13:06 -07:00
parent b7a962cc26
commit 84d3c33938
2 changed files with 76 additions and 0 deletions

25
lib/glacier/memory/move.h Normal file
View File

@ -0,0 +1,25 @@
#pragma once
namespace glcr {
template <typename T>
struct RemoveReference {
typedef T type;
};
template <typename T>
struct RemoveReference<T&> {
typedef T type;
};
template <typename T>
struct RemoveReference<T&&> {
typedef T type;
};
template <typename T>
typename RemoveReference<T>::type&& Move(T&& arg) {
return static_cast<typename RemoveReference<T>::type&&>(arg);
}
} // namespace glcr

View File

@ -0,0 +1,51 @@
#pragma once
namespace glcr {
template <typename T>
class UniquePtr {
public:
UniquePtr() : ptr_(nullptr) {}
UniquePtr(decltype(nullptr)) : ptr_(nullptr) {}
UniquePtr(T* ptr) : ptr_(ptr) {}
UniquePtr(const UniquePtr<T>&) = delete;
UniquePtr& operator=(const UniquePtr<T>&) = delete;
UniquePtr(UniquePtr<T>&& other) : ptr_(other.ptr_) { other.ptr_ = nullptr; }
UniquePtr& operator=(UniquePtr<T>&& other) {
T* temp = ptr_;
ptr_ = other.ptr_;
other.ptr_ = temp;
}
~UniquePtr() {
if (ptr_ != nullptr) {
delete ptr_;
}
}
explicit operator bool() const { return ptr_ != nullptr; }
bool empty() const { return ptr_ == nullptr; }
T* get() const { return ptr_; }
T* operator->() const { return ptr_; }
T& operator*() const { return *ptr_; }
T* release() {
T* tmp = ptr_;
ptr_ = nullptr;
return tmp;
}
private:
T* ptr_;
};
template <typename T, typename... Args>
UniquePtr<T> MakeUnique(Args... args) {
return UniquePtr(new T(args...));
}
} // namespace glcr