定义析构函数时,在复制构造函数调用中获取错误。如果未定义析构函数,则不会出现错误

时间:2017-02-11 16:09:07

标签: c++ c++11 constructor

当我在类中定义析构函数并尝试使用复制赋值构造函数时,我收到此错误。没有析构函数,复制赋值构造函数就可以正常工作。有人可以向我解释可能是什么问题吗?

“抛出'std :: bad_array_new_length'实例后调用终止   what():std :: bad_array_new_length“

以下是代码。尚未粘贴某些类函数和构造函数以避免过多代码。

class myvector
{
    int size;
    int *elem;

public:

    // constructor
    myvector(int size)
    {
        this->size = size;
        this->elem = new int[size]; 
    }

    // copy constructor
    myvector(const myvector &ob)
    {
        cout<<"copy constructor\n";

        try{
            elem = new int[ob.size];
        }catch(bad_alloc xa)
        {
            cout<<"Allocation failure. Please check heap memory\n";
        }

        for(int i=0; i<ob.size; i++)
            elem[i] = ob.elem[i]; 
    }

    // copy assignment constructor
    myvector& operator=(const myvector &ob)
    {
        cout<<"copy assignment constructor\n";
        if(this != &ob)
        {
            delete[] this->elem;
            this->size = ob.size;
            this->elem = new int[ob.size];

            for(int i=0; i<ob.size; i++)
                this->elem[i] = ob.elem[i];
        }

        return *this;
    }

    void update(int idx, int val)
    {
        elem[idx] = val;
    }

    int get(int idx)
    {
        return elem[idx];
    }

    int getSize()
    {
        return this->size;  
    }

    ~myvector()
    {
        cout<<"destructor \n";
        if(elem!=NULL)
            delete[] elem;
    }
};

int main()
{
    myvector ob1(5);
    myvector ob2(6);
    myvector x = ob1;
    myvector y = ob1;

    ob2.update(0, 15);

    // copy assignment constructor will be invoked
    ob2 = x;

    cout<<ob2.get(0)<<endl;
    cout<<x.get(0)<<endl;
    cout<<y.get(0)<<endl;
    return 0;   
}

0 个答案:

没有答案