object allocation question
Hi,
in many QT methods, for example the data() method of QAbstractTableModel (and many others) I am creating objects on the stack and returning them, like this:
Code:
Action *a;
int row_num,col_num;
col_num=index.column();
row_num=index.row();
if (row_num>
=actions
->count
()) return (QVariant());
a=actions->value(row_num);
if (a==0) {
}
if (role==Qt::DecorationRole) {
if (col_num==0) {
cat_action_id_t act_code;
act_code=a->get_action_code();
switch(act_code) {
case CAT_ACTION_UNDEFINED: {
break;
}
case CAT_ACTION_COMMENT : {
QPixmap icon
("/home/action_type_icons/comment.png");
return(icon);
break;
}
case CAT_ACTION_NEW_DEPENDENCY: {
QPixmap icon
("/home/action_type_icons/new_dependency.png");
return(icon);
break;
}
The "icon" variable is created on the stack and is destroyed after the method execution ends, but I am not getting segmentation faults in my app. The question is, how does it work ? Is QT copying all objects I am returning in the QT methods that I am overriding?
TIA.
Re: object allocation question
The method is returning an instance of QVariant.
The type QPixmap, is registered with the Qt variant type system.
For that it needs to be copyable.
So the QVariant instance contains a copy of the pixmap.
Since QPixmap is an implicitly shared class, copying it into the variant increments the pixmap's reference counter.
Destroying the local object decreased the reference counter.
The pixmap in the variant is then the only reference of the pixmap data.
Cheers,
_
Re: object allocation question
wow! amazing. thanks a lot for the clarification.