Вопрос

In my program I have to overload the = operator. The overloading function looks like:

Polygon &Polygon::operator=(const Polygon &source)
{
    this->capacity = source.capacity;
    this->index = source.index;
    this->vertex = new Vertex[source.capacity];

    for(int i = 0; i < source.capacity; i++)
    {
        this->vertex[i] = source.vertex[i];
    }

    return *this;
}

But if there is one thing I have learned is that I am responsible of deleting things i create with the "new" keyword.

So before returning I tried with:

delete vertex;

But that didn't work since it deletes the object which I just copied to. So I tried with:

delete source.vertex;

Which crashed my program during runtime.

I have tried alot of other ways also, but they are just tries with thought behind. I would really like your help, not only giving me what I should write, but how I should think in these scenarios.

Это было полезно?

Решение

Before this statement

this->vertex = new Vertex[source.capacity];

insert statement

delete [] this->vertex;

Also the operator must look the following way

Polygon &Polygon::operator=(const Polygon &source)
{
    if ( this != &source )
    {
       this->capacity = source.capacity;
       //...
    }

    return *this;
}

Другие советы

The program probably crashed because you used delete to delete a pointer created with operator new[] (not operator new). These are two different things. You always have to match the two, using delete[] with new[]:

int *p = new int;
delete p;

int *q = new int[10];
delete [] q;

You can't delete vertex there because the object is still referencing it. The destructor for Polygon should be responsible for deleting the Vertex objects it creates:

~Polygon::Polygon()
{
    if (vertex)
        delete[] vertex;
} 
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top