0

I am completely new to C++ and wanted to try and make a simple generic(not sure if this is proper terminology) array class which would essentially work as arrays in java(mainly for the handy length field). Here is all the code:

#include <iostream>


template <typename T>
class Array
{
private:
    T* ar;
public:
    const unsigned int length;

    Array(unsigned int length_) : length(length_), ar(new T[length]) {}
    void insert(unsigned int, T);
    T& get(unsigned int);
    T& operator[](unsigned int);
};

template <typename T> void Array<T>::insert(unsigned int index, T dataToAdd)
{
    if(index>=length)
        {throw -1;}
    ar[index]=dataToAdd;
}

template <typename T> T& Array<T>::get(unsigned int index)
{
    if(index>=length)
        {throw -1;}
    return ar[index];
}

template <typename T> T& Array<T>::operator[](unsigned int index)
    {return this->get(index);}


int main()
{
    std::cout << "main start\n";

    Array<int> nums1=Array<int>(2);
    nums1[0]=4;
    nums1[1]=10;
    std::cout << "length of nums1:" << nums1.length << "\n";    

    Array<int> nums2=Array<int>(2);
    nums2[0]=8;
    nums2[1]=5;
    std::cout << "length of nums2:" << nums2.length << "\n";

    Array<int> nums3=Array<int>(2);
    std::cout << "nums3 created\n";
    nums2[0]=3;
    std::cout << "added to index 0\n";
    nums2[1]=15;
    std::cout << "added to index 1\n";
    std::cout << "length of nums3:" << nums3.length <<"\n";

    std::cout << "main end\n";
}

It compiles just fine(using MinGW) but when I run it I get the following output:

main start
length of nums1:2
length of nums2:2
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

Since the last thing being printed by cout is length of nums2:2 I assume the exception is thrown on the line after: Array<int> nums3=Array<int>(2);

What is the reason for this? I can't be out of memory can I?

4

1 回答 1

3

Regardless of order on your initialization line, member variables are initialized in the order they are declared in the class. Thus this:

private:
    T* ar;
public:
    const unsigned int length;

means ar will be initialized before length, so this:

Array(unsigned int length_) : length(length_), ar(new T[length]) {}

is using length before it is constructed. Either change the class decl-order of member variables, or use length_ in the construction of ar.

于 2014-06-13T09:30:06.070 回答