V
V
vivieta2022-01-15 10:35:23
C++ / C#
vivieta, 2022-01-15 10:35:23

How to create a constructor for a dynamic array?

You need to create a constructor for the DynArray array with T* data and size_t size fields.

Move constructor with no exception guarantee.

I don't understand how to do this, please help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
robert_ford, 2022-01-16
@vivieta

#include <iostream>
template <typename T> class MyArray{
  T* arr;
  size_t size;
  public:
  MyArray(size_t size): size(size) {
    arr = new T[size];
  }

  MyArray(T* ptr, size_t size ):size(size), arr(ptr) {} 
  // деструктор
  ~MyArray(){ 
    if(arr == nullptr) return;
    delete[] arr;
  }

  // оператор перемещающего присваивания
  MyArray& operator=(T&& src) noexcept { 
    arr = src.arr;
    size = src.size;
    src.arr = nullptr;
    src.size = 0;
    return *this;
  }

// конструктор перемещения
  MyArray(MyArray&& src) noexcept:size(src.size), arr(src.arr) { 
    src.arr = nullptr;
    src.size = 0;
  }

  T& operator[](size_t idx) {
    if(idx > size - 1 || idx < 0) throw std::out_of_range("Index is out of range");
    return arr[idx];
  }

};

int main() {
  int* p = new int[5]{0,1,2,3,4};
  MyArray<int> a{p, 5};
  a[0] = 5;
  std::cout << a[0] << std::endl;
  MyArray<int> b(std::move(a));
  std::cout << b[0];
}

Here, following the rule of five, it would be nice to also implement a copy constructor and a copy assignment operator.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question