PDA

View Full Version : Problem with dynamic_cast



vratojr
11th April 2006, 18:40
Hi,even if the following code involves a bit of Qt I post it here because I think it's a more general problem.
The situation is the following:

I have a class that know its position inside an array:


class element{
public:
int position(){return pos;}
private:
int pos
}

A widget that contains it:


class widget : public QWidget{
public:
widget(element *elem):el(elem){};//I also pass parent to the constructor of qwiget
element* element(){return el;}
private:
element* el;
}


The principal widget is a QTabWidget and it contains a vector of elements.


class main : public QTabWidget{
private:
QVector<element> elements;
}

Using some slots, I create some elements and add them to the QVector (and coherently I set theirs pos memebers) and then use them to initialize widgets and add them to the tabwidget.


//inside main
addTab(new widget(&elements[i]);


Now,the problem. If from inside the tabwidget I want to access to *el inside widget (inside a particular tab) I have to use a dynamic cast.
So I use:
widget *w = dynamic_cast<widget*>(QTabWidget::widget(k));
if I then use w->position() to get its position, I sometimes get strange numbers.

It seems that,during the cast the pointer *el inside widget, became dangling...why?

Thanks!

jacek
11th April 2006, 19:10
It seems that,during the cast the pointer *el inside widget, became dangling...why?
Did you add something to that elements vector in the mean time?

vratojr
12th April 2006, 11:39
You mean "after the cast"? No,I didn't modify anything.

jacek
12th April 2006, 13:54
You mean "after the cast"? No,I didn't modify anything.
I meant this line "addTab(new widget(&elements[i]);". Do you add anything to that vector after creating those widgets?

vratojr
12th April 2006, 14:13
I APPEND other elements and I creat new widgets,nothing else.
Each time I create an element, I set the position variable and create the widget. nothing more.
I add that,for what I see, I got errors only after creating the first widget. I mean, the first is ok,the others may be wrong.

jacek
12th April 2006, 14:20
I APPEND other elements and I creat new widgets,nothing else.
Each time I create an element, I set the position variable and create the widget. nothing more.
I add that,for what I see, I got errors only after creating the first widget. I mean, the first is ok,the others may be wrong.
When you add elements to a QVector (or std::vector), it sometimes must allocate more space for new elements and to achieve that it might have to move all elements to another place in the memory. If this happens, all pointers to previous elements will be invalid.

vratojr
12th April 2006, 14:34
Argh!Yeah! I've read this just some days ago...;)
Thank you very much!

jacek
12th April 2006, 14:45
You can either reserve enough space before you add elements (if you know their exact number) or use a vector of pointers.