0

I am getting this error when i define a destructor in the class and try to use copy assignment constructor. Without destructor, copy assignment constructor works just fine. Can someone explain to me what could be the issue?

"terminate called after throwing an instance of 'std::bad_array_new_length' what(): std::bad_array_new_length"

Below is the code. Some of the class functions and constructors have not been pasted to avoid too much code.

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;   
}
  • You haven't got a copy constructor in that code. –  Feb 11 '17 at 16:10
  • Note: I second-guessed the duplicate, in the absence of a [mcve]. The error message hints at a different issue though. – juanchopanza Feb 11 '17 at 16:13
  • @himanshu0811 -- *copy assignment constructor* -- That is not a constructor. The word *constructor* in C++ has a specific meaning. You do not have a copy constructor. In addition, just posting class code does not show us how you're using this class. Please post a [mcve] – PaulMcKenzie Feb 11 '17 at 16:18
  • @PaulMcKenzie.. sorry about any confusion. Have posted Minimal, Complete, and Verifiable example – himanshu0811 Feb 11 '17 at 16:28
  • You failed to copy `ob.size` in your copy constructor. In addition, your `try / catch` for the copy constructor doesn't make sense, since you just keep going as if nothing is wrong if there is a `bad_alloc` thrown. – PaulMcKenzie Feb 11 '17 at 16:32

0 Answers0