c++arraysstatic-memory-allocation

C++ Compiling Static Arrays of Unknown Type


Here is my code:

template<typename T, std::size_t N>
    class my_array {
    public:
        const T& at(std::size_t index) const
        {
            if(index>N) throw std::out_of_range("Index is wrong. Try again");
            return data[index];
        }
        
        ...

        my_array()
        {
            T data[N];
        }
        ~my_array()
        {
            delete[] data;
        }

    private:
        T* data;
    };

In the my_array() method I want to create a static array of type T, but I don't really understand how. For example, this way doesn't work.

I tried to do it the way I wrote above, I also tried to use typedef, though I may have done it wrong, but none of the ways worked.

How do I make it work?


Solution

  • I guess what you want to do is to create an array on the stack, just like std::array? If so, you can do it just like this:

    template<typename T, std::size_t N>
    class my_array {
    public:
        const T& at(std::size_t index) const
        {
            if (index >= N) throw std::out_of_range("Index is wrong. Try again");
            return data[index];
        }
    
        my_array() = default;
        ///~my_array() = default;    // dont write this
    
    private:
        T data[N];
    };
    

    Note that you should not call delete on the array, because you didnt allocate memory with new. Since there is no memory allocation with new going on here, you can just create an empty constructor and destructor, or specify it with my_array() = default; like I did.

    As some comment already said, you could be accessing an element out of bounds in your at() method. Use index >= N instead (arrays go from 0 to N-1).

    By the way you can just open the file array from the STL and take a look at its implementation. They have defined their data like this _Ty _Elems[_Size];.


    Edit:

    As the comments on this answer state, you shouldnt be defining a destructor for the class, if its gonna be empty anyways. With writing something like ~my_array() = default; or my_array(){} and not specifying a move constructor, the data will always be copied instead of moved.