Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <exception>
- #include <functional>
- #include <optional>
- #include <cstddef>
- #include <memory>
- template <typename T, typename del = std::default_delete<T>>
- class UniquePtr {
- private:
- std::tuple<T*, del> ptr;
- public:
- UniquePtr() {
- std::get<0>(ptr) = nullptr;
- }
- UniquePtr(T* smth) {
- std::get<0>(ptr) = smth;
- }
- UniquePtr(UniquePtr<T>&& another) noexcept {
- std::get<0>(ptr) = another.ptr;
- std::get<0>(another.ptr) = nullptr;
- }
- UniquePtr(T* smth, del deleter) {
- std::get<0>(ptr) = smth;
- std::get<1>(ptr) = deleter;
- }
- UniquePtr& operator=(std::nullptr_t it_is_nullptr) {
- std::get<1>(ptr)(std::get<0>(ptr));
- std::get<0>(ptr) = it_is_nullptr;
- return *this;
- }
- UniquePtr& operator= (UniquePtr<T>&& another) noexcept {
- std::swap(std::get<0>(another.ptr), std::get<0>(ptr));
- another.std::get<1>(ptr)(std::get<0>(another.ptr));
- another.std::get<0>(ptr) = nullptr;
- return *this;
- }
- T& operator*() const {
- return *std::get<0>(ptr);
- }
- T* operator->() const noexcept {
- return std::get<0>(ptr);
- }
- T * release() noexcept {
- T * to_give = nullptr;
- std::swap(to_give, std::get<0>(ptr));
- return to_give;
- }
- void reset(T * ptr_) noexcept {
- std::get<1>(ptr)(std::get<0>(ptr));
- std::get<0>(ptr) = ptr_;
- }
- void swap(UniquePtr& other) noexcept {
- std::swap(std::get<0>(other.ptr), std::get<0>(ptr));
- }
- T * get() const noexcept {
- return std::get<0>(ptr);
- }
- explicit operator bool() const noexcept {
- return static_cast<bool>(std::get<0>(ptr));
- }
- del& get_deleter() {
- return std::get<1>(ptr);
- }
- const del& get_deleter() const {
- return std::get<1>(ptr);
- }
- ~UniquePtr() {
- std::get<1>(ptr)(std::get<0>(ptr));
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement