user3699546
user3699546

Reputation: 133

Allocating an array in a templated class

The template I'm using is

template<typename T, size_type MAX_DIM = 500>

I am trying to figure out how to allocate correctly. The variable T ** array_ is declared in the constructor. This is what I have right now, but I've tried a few different kinds of syntax to no avail.

array_=new value_type*[dim1_];
    for ( long i = 0u; i < dim1_; i++)
        array_[i] = new value_type[dim2_];

Upvotes: 0

Views: 33

Answers (1)

Jack
Jack

Reputation: 133609

I don't understand why you are using value_type when the template argument is T just use it:

template<typename T, size_t MAX_SIZE = 500>
class MyArray
{
    T** array_;
public:
    MyArray(size_t dim1_, size_t dim2)
    {
        array_ = new T*[dim1_];
        for (size_t i = 0; i < dim2; ++i)
          array_[i] = new T[dim2];
    }
};

Mind that since you are not using std::vector nor std::array you will need to release memory manually through delete [] in the destructor.

Upvotes: 1

Related Questions