Open alexey-malov opened 7 years ago
CMyArray(size_t size)
{
if (size != 0)
{
m_begin = RawAlloc(size);
m_end = m_begin;
m_endOfCapacity = m_begin + size;
}
}
[ ] В стандартном классе vector конструктор с параметром size_t создает массив из заданного количества инициализированных по умолчанию элементов. Здесь же работает как reserve. Сделать как в стандартном
[ ] Этот конструктор должен быть объявлен explicit.
CMyArray(std::initializer_list<T> initList)
CMyArray(std::initializer_list<T> initList)
{
const auto size = initList.size();
if (size != 0)
{
m_begin = RawAlloc(size);
try
{
CopyItems(initList.begin(), initList.end(), m_begin, m_end);
m_endOfCapacity = m_end;
}
catch (...)
{
DeleteItems(m_begin, m_end);
throw;
}
}
}
CMyArray(const CMyArray& arr)
{
const auto size = arr.GetSize();
if (size != 0)
{
m_begin = RawAlloc(size);
try
{
CopyItems(arr.m_begin, arr.m_end, m_begin, m_end);
m_endOfCapacity = m_end;
}
catch (...)
{
DeleteItems(m_begin, m_end);
throw;
}
}
}
void Resize(size_t size)
{
if (size != GetSize())
{
CMyArray<T> temp(size);
size_t copiesCount = std::min(GetSize(), size);
for (size_t i = 0; i < copiesCount; ++i)
{
temp.Append(*(m_begin + i));
}
for (size_t i = GetSize(); i < size; ++i)
{
temp.Append(T());
}
*this = std::move(temp);
}
}
[ ] При уменьшении размеров массива должно произойти лишь удаление лишних элементов
[ ] При увеличении размеров до величины, не превышающей capacity не должно происходить копирование уже существующих элементов. Только конструирование новых.
[ ] Лишь при увеличии размеров массива свыше capacity должно происходить полное копирование элементов массива на новое место.
Рекомендую посмотреть видео vector с нуля с конференции с++ russia 2016 http://cpp-russia.ru/?page_id=1022
void Clear()
{
DeleteItems(m_begin, m_end);
m_begin = nullptr;
m_end = nullptr;
m_endOfCapacity = nullptr;
}
CMyArray& operator=(CMyArray& arr)
{
if (std::addressof(arr) != this)
{
CMyArray copy(arr);
std::swap(m_begin, copy.m_begin);
std::swap(m_end, copy.m_end);
std::swap(m_endOfCapacity, copy.m_endOfCapacity);
}
return *this;
}
пример, когда приходится объявлять пустой деструктор и конструктор (внутри класса используется неполно объявленный тип (incomplete type))
abc.h:
class X;
class Y
{
Y();
~Y();
unique_ptr<X> m_x;
}
abc.cpp:
#include "x.h"
Y::Y()
{
}
Y::~Y()
{
}