points not accessible after QVector insert function

307 views Asked by At

I am trying to follow the rule of three, however doing this has cause a problem specifically with QVector's insert function.

after adding a copy constructor and destructor, My program will produce an error where a vector of points are no longer accessible, and so the copy constructor fails to re-assign the points.

Here are some snippets from my code

QVector<QPointF> *mList = nullptr;
int area;

Shape::Shape()
{
    mList = new QVector<QPointF>();
    area = 0;
}
Shape::Shape(const Shape &obj)
{
    mList = new QVector<QPointF>();
    mList = *obj.mList;
    area = obj.area;
}
Shape::~Shape()
{
    delete mList;
}

Now I sort a group of 'Shape' objects by their area using qSort, which uses the QVector functions.

void T::sortByArea()
{     
    qSort(listOfShapes);
}

When this method finishes. I find that one of the shapes now has an mList that has the value <not accessible>. Which only occurs in the sort when QVector::insert(int i, const T &value) is used.


Up until this point, this list of shapes is edited and manipulated but this is the only time up to this point that a Shape's list becomes inaccessible. What is the reasoning and how should I fix this?

1

There are 1 answers

0
mahesh On

As far as I can see, since you use const in your copy constructor argument list, the QVector is only shallow copied and not deep copied. This is because QVector is an implicitly shared container.

Removing the const should work, but better solution may be to explicitely copy the entire vector (eg. using memcopy), not just using the QVector's = operator.