[ox/std] Add UniquePtr

This commit is contained in:
Gary Talent 2021-04-20 22:09:52 -05:00
parent a16b56325d
commit 2b579c58bb
3 changed files with 113 additions and 0 deletions

View File

@ -71,6 +71,7 @@ install(
heapmgr.hpp heapmgr.hpp
math.hpp math.hpp
memops.hpp memops.hpp
memory.hpp
new.hpp new.hpp
random.hpp random.hpp
std.hpp std.hpp

111
deps/ox/src/ox/std/memory.hpp vendored Normal file
View File

@ -0,0 +1,111 @@
/*
* Copyright 2015 - 2021 gary@drinkingtea.net
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include "utility.hpp"
namespace ox {
template<typename T>
class UniquePtr {
private:
T *m_t;
public:
explicit constexpr UniquePtr(T *t = nullptr) noexcept: m_t(t) {
}
constexpr UniquePtr(const UniquePtr&) = delete;
template<typename U>
constexpr UniquePtr(UniquePtr<U> &&other) noexcept {
m_t = other.release();
}
~UniquePtr() {
delete m_t;
}
constexpr T *release() noexcept {
auto t = m_t;
m_t = nullptr;
return t;
}
[[nodiscard]]
constexpr T *get() const noexcept {
return m_t;
}
constexpr void reset(UniquePtr &&other = UniquePtr()) {
auto t = m_t;
m_t = other.m_t;
other.m_t = nullptr;
delete t;
}
constexpr UniquePtr &operator=(UniquePtr &&other) {
reset(ox::move(other));
return *this;
}
constexpr T *operator->() const noexcept {
return m_t;
}
constexpr T &operator*() const noexcept {
return *m_t;
}
constexpr operator bool() const noexcept {
return m_t;
}
};
template<typename T>
constexpr bool operator==(const UniquePtr<T> p1, const UniquePtr<T> p2) noexcept {
return p1.get() == p2.get();
}
template<typename T>
constexpr bool operator==(const UniquePtr<T> p1, std::nullptr_t) noexcept {
return p1.get();
}
template<typename T>
constexpr bool operator==(std::nullptr_t, const UniquePtr<T> p2) noexcept {
return p2.get();
}
template<typename T>
constexpr bool operator!=(const UniquePtr<T> p1, const UniquePtr<T> p2) noexcept {
return p1.get() != p2.get();
}
template<typename T>
constexpr bool operator!=(const UniquePtr<T> p1, std::nullptr_t) noexcept {
return !p1.get();
}
template<typename T>
constexpr bool operator!=(std::nullptr_t, const UniquePtr<T> p2) noexcept {
return !p2.get();
}
template<typename T, typename ...Args>
[[nodiscard]]
constexpr auto make_unique(Args&&... args) noexcept {
return UniquePtr(new T(args...));
}
}

View File

@ -20,6 +20,7 @@
#include "heapmgr.hpp" #include "heapmgr.hpp"
#include "math.hpp" #include "math.hpp"
#include "memops.hpp" #include "memops.hpp"
#include "memory.hpp"
#include "new.hpp" #include "new.hpp"
#include "random.hpp" #include "random.hpp"
#include "stacktrace.hpp" #include "stacktrace.hpp"