Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // author @asad_nitp
- #pragma once
- namespace Smart_Pointers {
- template<typename T>
- class Unique_Ptr {
- T* m_ptr;
- public:
- explicit Unique_Ptr(T* ptr = nullptr) noexcept
- : m_ptr(ptr)
- {}
- ~Unique_Ptr() noexcept {
- if (m_ptr != nullptr) {
- delete m_ptr;
- }
- m_ptr = nullptr;
- }
- Unique_Ptr(const Unique_Ptr&) = delete;
- Unique_Ptr& operator = (const Unique_Ptr&) = delete;
- Unique_Ptr(Unique_Ptr&& ob) noexcept {
- m_ptr = ob.m_ptr;
- ob.m_ptr = nullptr;
- }
- Unique_Ptr& operator = (Unique_Ptr&& ob) noexcept {
- if (this != &ob) {
- m_ptr = ob.m_ptr;
- ob.m_ptr = nullptr;
- }
- return *this;
- }
- T* operator -> () const noexcept {
- return m_ptr;
- }
- T& operator * () const {
- return *m_ptr;
- }
- T* get() const noexcept{
- return m_ptr;
- }
- T* release() noexcept {
- T* ans = m_ptr;
- m_ptr = nullptr;
- return ans;
- }
- void reset(T* ptr = nullptr) noexcept {
- T* old = m_ptr;
- m_ptr = ptr;
- if (old != nullptr)
- delete old;
- }
- void swap(Unique_Ptr& ob) noexcept {
- using std::swap;
- swap(m_ptr,ob.m_ptr);
- }
- };
- }
- //Examples
- int main() {
- Smart_Pointers::Unique_Ptr<int> up1(new int(5));
- Smart_Pointers::Unique_Ptr<int> up2(new int(6));
- up1 = up2; // Error
- up1 = std::move(up2); //fine
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement