nochnoikoshmar1

array_ptr.h

May 28th, 2023
97
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <numeric>
  4. #include <iostream>
  5. #include <cassert>
  6.  
  7. template <typename Type>
  8. class ArrayPtr{
  9. public:
  10.     ArrayPtr() = default;
  11.  
  12.     explicit ArrayPtr(size_t size){
  13.         if(size == 0){
  14.             raw_ptr_ = nullptr;
  15.             return;
  16.         }
  17.         try{
  18.             raw_ptr_ = new Type[size]();
  19.         }
  20.         catch(...){
  21.             raw_ptr_ = nullptr;
  22.             throw;
  23.         }
  24.     }
  25.     ArrayPtr(ArrayPtr &&other) noexcept
  26.         : raw_ptr_(other.Release()){}
  27.  
  28.     explicit ArrayPtr(Type *raw_ptr) noexcept{
  29.         raw_ptr_ = raw_ptr;
  30.     }
  31.  
  32.     ArrayPtr(const ArrayPtr &) = delete;
  33.  
  34.     ~ArrayPtr(){
  35.         delete[] raw_ptr_;
  36.     }
  37.  
  38.     ArrayPtr &operator=(const ArrayPtr &rhs) = delete;
  39.  
  40.     ArrayPtr &operator=(ArrayPtr &&rhs)noexcept{
  41.         if(raw_ptr_ != nullptr){
  42.             delete[] raw_ptr_;
  43.         }
  44.         raw_ptr_ = std::exchange(rhs.raw_ptr_, nullptr);
  45.         return *this;
  46.     }
  47.  
  48.     [[nodiscard]] Type *Release() noexcept{
  49.         Type *t = raw_ptr_;
  50.         raw_ptr_ = nullptr;
  51.         return t;
  52.     }
  53.  
  54.     Type &operator[](size_t index) noexcept{
  55.         return raw_ptr_[index];
  56.     }
  57.  
  58.     const Type &operator[](size_t index) const noexcept{
  59.         return raw_ptr_[index];
  60.     }
  61.  
  62.     explicit operator bool() const{
  63.         return raw_ptr_ != nullptr;
  64.     }
  65.  
  66.     Type *Get() const noexcept{
  67.         return raw_ptr_;
  68.     }
  69.  
  70.     void swap(ArrayPtr &other) noexcept{
  71.         // Реализуйте метод самостоятельно
  72.         std::swap(raw_ptr_, other.raw_ptr_);
  73.     }
  74.  
  75. private:
  76.     Type *raw_ptr_ = nullptr;
  77.     size_t size_;
  78. };
Tags: v1 array_ptr.h
Advertisement
Comments
Add Comment
Please, Sign In to add comment