Reputation: 1288
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:
Upvotes: 0
Views: 152
Reputation: 4959
Returning a pointer to a memory address inside the QList storage is ill-advised. From the QList documentation "be aware that any non-const function call performed on the QList will render all existing iterators undefined". If the inner container stored actual pointers then that would not be a problem. These could even be smart pointers that eliminate the need of writing a destructor.
However I also see that you are passing by value to add an item. If passing by value is acceptable there then why not for the return? This is an inconsistent interface.
It sounds like you want to really want to pass and return by reference, e.g. add(const MyItem&)
and MyItem& get(int)
.
As noted by rafix, QList's operator[](idx)
returns a non const reference, so you can simply return that.
Then how will you do bounds checking? There are multiple ways but the easiest is to just add a size()
method.
Upvotes: 1