dimanche 28 février 2021

Qt C++11 Handing out raw pointer from QList

I am working on a problem where I have some sort of custom made "container" DTO which contains a series of items. The user of the class should be able to retrieve an item at a position from the container. I wanted the container to not keep a refrence of raw pointers to the items it contains, but really own them so no custom destructor is necessary. This is what I came up with:

#include <QList>

class MyItem {

public:
    MyItem(int n) : number(n){}

private:
    int number;
};

class MyContainer {

public:
    void addItem(MyItem item){
        m_items.append(item);
    }

    MyItem* getItemAt(int pos){
           if(pos < m_items.size() && pos >= 0){
                return &(m_items.at(pos));
           }
           return nullptr;
    }

private:
    QList<MyItem> m_items;

};


int main(){

    MyContainer container;

    MyItem item1(4);
    container.addItem(item1);

    MyItem* item_ptr = container.getItemAt(0);
    return 0;
}

And in the return of the getItemAt function I am getting this error:

main.cpp:21:24: error: cannot initialize return object of type 'MyItem *' with an rvalue of type 'const MyItem *'

My function needs to return a non const value, because the caller needs to modify the retrieved object. Is there a way to fix this? Is this the best solution for avoiding the destructor and indicating to the caller that the return value is empty.

I know there are several ways to do this:

  • return an optional: unfortunately I am bound to C++11 so not an option
  • throw an exception: I really dislike this option since the codebase has 0 exceptions atm, and I rather not introduce them here.

Aucun commentaire:

Enregistrer un commentaire