Skip to content

Instantly share code, notes, and snippets.

@iboB
Last active November 7, 2019 10:12
Show Gist options
  • Save iboB/c359d4ff542022543440f2e774e053e2 to your computer and use it in GitHub Desktop.
Save iboB/c359d4ff542022543440f2e774e053e2 to your computer and use it in GitHub Desktop.
namespace my {
template <typename T>
class unique_ptr {
public:
using pointer = T*;
unique_ptr() noexcept = default;
unique_ptr(std::nullptr_t) noexcept {}
explicit unique_ptr(pointer p) noexcept : m_ptr(p) {}
unique_ptr(unique_ptr&& other) noexcept : m_ptr(other.release()) {}
unique_ptr(const unique_ptr&) = delete;
~unique_ptr() {
delete m_ptr;
}
unique_ptr& operator=(unique_ptr&& other) noexcept {
reset(other.release());
return *this;
}
unique_ptr& operator=(std::nullptr_t) noexcept {
reset();
return *this;
}
unique_ptr& operator=(const unique_ptr&) = delete;
pointer release() noexcept {
auto old = m_ptr;
m_ptr = nullptr;
return old;
}
void reset(pointer p = nullptr) noexcept {
auto old = m_ptr;
m_ptr = p;
delete old;
}
explicit operator bool() const noexcept { return !!m_ptr;}
pointer get() const noexcept { return m_ptr; }
T& operator*() const { return *m_ptr; }
T* operator->() const noexcept { return m_ptr; }
private:
pointer m_ptr = nullptr;
};
template <typename T, typename... Args>
unique_ptr<T> make_unique(Args&&... args) {
return unique_ptr<T>{new T(std::forward<Args>(args)...)};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment