为什么抛出这个bad_alloc异常?

时间:2014-06-13 09:25:31

标签: c++ bad-alloc

我是C ++的新手,想要尝试制作一个简单的通用(不确定这是否是正确的术语)数组类,它本质上可以作为java中的数组(主要用于方便的长度字段)。 以下是所有代码:

#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";
}

它编译得很好(使用MinGW),但是当我运行它时,我得到以下输出:

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.

由于cout打印的最后一件事是 nums2:2 的长度,我认为在Array<int> nums3=Array<int>(2);

之后的行上会抛出异常

这是什么原因?我不能不记忆吗?

1 个答案:

答案 0 :(得分:3)

无论初始化行的顺序如何,成员变量都按照它们在类中声明的顺序进行初始化。因此:

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

表示ar将在length之前初始化,因此:

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

在构建之前使用length。要么更改成员变量的类decl-order,要么在构造length_时使用ar