Search code examples
c++qtqvector

Creating and accessing elements of a QVector of pointers to QObjects


I try adding pointers to objects to a QVector but when I access the QVector later it appears to be empty.

Here is a stripped down version of the code with the problem where the Villain class has a QVector of Minion*.

void Widget::mainFunction()
{
    int totalMinions = 5;
    for(int i = 0; i < totalMinions; i++)
    {
        evilOrganisation.getVillain().addMinion();
    }

    for(int i = 0; i < totalMinions; i++)
    {
        qDebug() << "Minion " << i << " Has " << evilOrganisation.getVillain().getMinion(i)->getNumItems()<< " items";
    }
}

The ultimate goal is to get the number of items from each minion

#include <QObject>
#include "villain.h"

class EvilOrganisation : public QObject
{
    Q_OBJECT
public:
    explicit EvilOrganisation(QObject *parent = 0);

    Villain getVillain(){return villain;}

private:
    Villain villain;

}; 

__

#include <QVector>
#include "minion.h"

class Villain
{
public:
    Villain();

    void addMinion(){minions.append(new Minion());} 

    Minion* getMinion(int i){return minions.at(i);} 

private:
    QVector<Minion*> minions;
};

addMinion() successfully appends 1 Minion* but the next time the function is called minions is empty.

getMinion(int i) crashes the program because minions.at(i) doesn't exist. Where the error message is - ASSERT failure in QVector::at: "index out of range"

#include <QObject>

class Minion : public QObject
{
    Q_OBJECT
public:
    explicit Minion(QObject *parent = 0);

    int getNumItems(){return items;}

private:
    int items = 1;
};

So why does minions.append(new Minion()) appear to work but the minions QVector appear empty every time I try to access it?


Solution

  • You have to implement the Villain copy-constructor. Every time EvilOrganisation::getVillain() is called you will get a copy of your class member - the Villain object, which contains an emptyQVector` by default.

    Another idea is to just return a reference to your Villain like in

    Villain& getVillain() {
        return villain;
    }