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?
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:Note that you should not call
deleteon the array, because you didnt allocate memory withnew. Since there is no memory allocation withnewgoing on here, you can just create an empty constructor and destructor, or specify it withmy_array() = default;like I did.As some comment already said, you could be accessing an element out of bounds in your
at()method. Useindex >= Ninstead (arrays go from 0 to N-1).By the way you can just open the file
arrayfrom 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;ormy_array(){}and not specifying a move constructor, the data will always be copied instead of moved.