Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created January 24, 2015 22:59
Show Gist options
  • Save dgodfrey206/3daf6cdee0b21b62a19d to your computer and use it in GitHub Desktop.
Save dgodfrey206/3daf6cdee0b21b62a19d to your computer and use it in GitHub Desktop.
Dumb array
#include <iostream>
#include <algorithm>
template<class T>
class dumb_array
{
public:
dumb_array(std::size_t size = 0) noexcept(noexcept(T()))
: m_size(size)
, m_array(size ? new T[m_capacity]() : 0)
{ }
dumb_array(dumb_array const& other) noexcept(noexcept(T()))
: m_size(other.m_size)
, m_array(m_size ? new T[other.m_capacity]() : 0)
{
std::copy(other.m_array, other.m_array + m_size, m_array);
}
dumb_array(dumb_array&& other) noexcept
: dumb_array()
{
swap(*this, other);
}
dumb_array& operator=(dumb_array rhs) noexcept
{
swap(*this, rhs);
return *this;
}
~dumb_array() noexcept(noexcept(std::declval<T>().~T()))
{
delete[] m_array;
}
friend void swap(dumb_array& lhs, dumb_array& rhs) noexcept
{
using std::swap;
swap(lhs.m_array, lhs.m_array);
swap(lhs.m_size, lhs.m_size);
}
template<class U>
void push_back(U&& value)
{
if (size() == capacity())
m_resize(m_capacity << 1);
m_array[m_size++] = std::forward<U>(value);
}
std::size_t size() const noexcept { return m_size; }
std::size_t capacity() const noexcept { return m_capacity; }
private:
std::size_t m_size;
T* m_array;
std::size_t m_capacity = 0;
private:
void m_resize(std::size_t new_capacity)
{
m_capacity = m_capacity ? new_capacity : 1;
T* newArray = new T[m_capacity];
delete[] m_array;
m_array = newArray;
}
};
int main()
{
dumb_array<int> a1;
for (int i = 0; i < 50; ++i)
a1.push_back(i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment