ulfben

Container 2020 day 1

Nov 17th, 2020 (edited)
656
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. #pragma once
  2. #include <algorithm>
  3. #include <numeric>
  4. namespace API
  5. {
  6.     class Container
  7.     {
  8.     public:
  9.         using iterator = int*; //aliases for generic code
  10.         friend void swap(Container& a, Container& b) noexcept;
  11.  
  12.         Container() = default;
  13.         explicit Container(size_t count) : _count(count), _data(new int[count]){
  14.             std::iota(begin(), end(), 0);
  15.         };
  16.  
  17.         explicit Container(const Container& that) { //copy ctor        
  18.             _data = new int[that._count];
  19.             _count = that._count;          
  20.             std::copy(that.begin(), that.end(), _data);
  21.         }
  22.  
  23.         Container(Container&& that) noexcept {
  24.             _count = that._count;
  25.             _data = that._data;
  26.             that._data = nullptr;
  27.             that._count = 0;
  28.         }
  29.  
  30.         Container& operator=(Container&& that) noexcept {
  31.             std::swap(_data, that._data);          
  32.             std::swap(_count, that._count);        
  33.             return *this;
  34.         }
  35.        
  36.         void swap(Container& that) noexcept {
  37.             using std::swap;
  38.             swap(_data, that._data);
  39.             swap(_count, that._count);
  40.         }
  41.  
  42.         Container& operator=(const Container& that) { // copy assignment
  43.             delete[] _data;
  44.             _data = new int[that._count]; //overwrites an existing pointer
  45.             _count = that._count;
  46.             std::copy(that.begin(), that.end(), _data);
  47.             return *this;          
  48.         }
  49.        
  50.         ~Container() {
  51.             delete[] _data;
  52.         }
  53.  
  54.         iterator begin() const noexcept { return _data; }
  55.         iterator end() const noexcept { return _data + _count; }
  56.  
  57.  
  58.     private:
  59.         int* _data = nullptr;
  60.         size_t _count = 0;
  61.     };
  62.  
  63.     void swap(Container& a, Container& b) noexcept {
  64.         a.swap(b);
  65.     }
  66. }
Add Comment
Please, Sign In to add comment