-1
\$\begingroup\$

As a conceptual implementation of the default c++ std array interface, would this be a suitable implementation & what is the safety of this implementation?

template<typename T> 
class Array
{
private:
    T* arr;
public:
    Array(const size_t size)
    {
        arr = (T*)malloc(sizeof(T) * size);
    }
    ~Array()
    {
        free(arr);
    }
    T& operator[](size_t index) const
    {
        return arr[index];
    }
};
\$\endgroup\$
1
  • \$\begingroup\$ There’s an issue here also if T requires initialization (i.e. it’s something different from a numeric type). \$\endgroup\$ Commented Jun 11, 2018 at 1:07

1 Answer 1

1
\$\begingroup\$

The code you provided is more like a vector rather than an array. An array's size is specified at compile-time (is fixed). Hence the most basic implementation would be:

#include <cstddef>

template<typename type, std::size_t size>
struct array
{
  type data[size];
};
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.