Reputation: 1322
I wrote a small piece of code to prove to myself some bad practice was indeed bad practice. However I'm not seeing the result I expected. I have a QList storing objects rather than pointers to those objects. Here is the class:
class test{
public:
test(int value){val=value; printf("created test %d\n",val);}
~test(){ printf("deleting test %d\n", val); val=0;}
void print(){printf("test %d!\n", val);}
int val;
};
and I have a list of these with test functions as follows:
class myclass {
...
QList<test> _test_list;
void do_test_init();
void do_test();
...
};
void myclass::do_test_init()
{
for(int i=0; i < 10; i++)
_test_list.append(test(i+100));
}
void myclass::do_test()
{
for(int i=0; i < 10; i++)
_test_list[i].print();
}
The output I see is:
created test 100
deleting test 100
created test 101
deleting test 101
created test 102
deleting test 102
created test 103
deleting test 103
created test 104
deleting test 104
created test 105
deleting test 105
created test 106
deleting test 106
created test 107
deleting test 107
created test 108
deleting test 108
created test 109
deleting test 109
test 100!
test 101!
test 102!
test 103!
test 104!
test 105!
test 106!
test 107!
test 108!
test 109!
I'm assuming this is because the append function is taking a copy of the object I passed in. Does this mean that it's safe to use QList this way? My preference is to store pointers rather than objects, is this misguided?
Upvotes: 0
Views: 206
Reputation: 1322
The answer to this question is that it's perfectly "safe" in the sense that the object is copied when it is appended to the list. Providing a copy constructor shows this clearly. The copied objects are deleted when the list is cleared.
Upvotes: 2