Qt-interest Archive, August 2006
problem with constructor
Message 1 in thread
i think i've run into this issue before, but it was a long time ago
and i can't remember what the problem turned out to be.
i've implemented a class with a constructor that takes as one of its
arguments a pointer to a QWidget (ie: QWidget * thewidget).
inside the constructor i do something like this:
thewidget = new QWidget;
that goes fine: memory is properly allocated and the pointer is
valid... that is until i return out of the constructor back to the
calling code. if i then try to use the new instance of the QWidget, i
get a segmentation fault.
printing out the pointer address before the constructor call, inside
the constructor (just after calling new QWidget), and just after the
call to the constructor, shows that the pointer is first NULL, then
valid, then NULL again (respectively). if i don't initialize the
pointer before the call, it's junk, then valid, then the exact same
junk again (respectively).
please point out what i'm doing wrong here:
Thingy::Thingy ( QWidget * thewidget )
: ThingysMommy()
{
......
printf("B (%p)\n", thewidget);
fflush(stdout);
thewidget = new QWidget;
printf("C (%p)\n", thewidget);
fflush(stdout);
......
}
... and the calling code looks like:
......
QWidget * widget;
printf("A (%p)\n", widget);
fflush(stdout);
Thingy thing(widget);
printf("D (%p)\n", widget);
fflush(stdout);
widget->doSomething(); // causes segmentation fault
......
... the output looks like:
A (0x44002442) // uninitialized junk
B (0x44002442) // uninitialized junk
C (0x10043C98) // valid
D (0x44002442) // back to exact same uninitialized junk
how do i get the address to stick.
thanks.
- chase
Message 2 in thread
> please point out what i'm doing wrong here:
>
> Thingy::Thingy ( QWidget * thewidget )
> : ThingysMommy()
> {
> ......
> printf("B (%p)\n", thewidget);
> fflush(stdout);
>
> thewidget = new QWidget;
>
> printf("C (%p)\n", thewidget);
> fflush(stdout);
> ......
> }
>
>
> ... and the calling code looks like:
>
> ......
> QWidget * widget;
>
> printf("A (%p)\n", widget);
> fflush(stdout);
>
> Thingy thing(widget);
If you really want 'widget' to retain the value assigned to
it in the Thingy c'tor you need to pass the widget pointer
as reference, not as value, i.e.:
Thingy::Thingy ( QWidget * & thewidget )
: ThingysMommy()
It'd not what I'd call 'good style' though even if it will
work.
Constructing the widget outside would already be better
as far as I am concerned:
> Thingy::Thingy ( QWidget * thewidget )
> : ThingysMommy()
> {
> ......
> printf("B (%p)\n", thewidget);
> fflush(stdout);
>
> printf("C (%p)\n", thewidget);
> fflush(stdout);
> ......
> }
>
>
> ......
> QWidget * widget = new QWidget(...)
>
> printf("A (%p)\n", widget);
> fflush(stdout);
>
> Thingy thing(widget);
>
> printf("D (%p)\n", widget);
> fflush(stdout);
>
> widget->doSomething(); // causes segmentation ! fault
> ......
Andre'
--
[ signature omitted ]