简体   繁体   English

带有 QWidget 的分段错误构造函数。 Qt/C++

[英]Segmentation Fault constructor with QWidget. Qt/C++

I have this problem.我有这个问题。 Sometimes (but very rarely) my program crash on starting.有时(但很少)我的程序在启动时崩溃。 The QDebugger points to the segmentation fault originating from this code: QDebugger 指向源自此代码的分段错误:

view_add_bagagli::view_add_bagagli(QWidget*parent):QWidget(parent),setBagWid(new QWidget_add_lug(this)),
setPropWid(new QWidget_add_owner(this)),
setViaWid(new QWidget_add_travel(this)){} // segm fault at this line

And this is the code of QWidget_add_travel 's constructor:这是 QWidget_add_travel 的构造函数的代码:

QWidget_add_travel::QWidget_add_travel(QWidget *parent) : Qwidget(parent),via_l(new QVBoxLayout()){
    setLayout(via_l);
    build();
}

But QDebugger did NOT indicate segmentation faults in this code.但是 QDebugger 没有指出这段代码中的分段错误。 The strangest thing is the segmentation fault happens sometimes (very rarely) and NOT every time!最奇怪的是分段错误有时(很少)发生,而不是每次都发生! Maybe this is not a good question, but I am very confused about this error.也许这不是一个好问题,但我对这个错误感到非常困惑。

You are not calling the QWidget constructor in your constructor (I'm assuming QWidget is the superclass of QWidget_add_travel ).您没有在构造函数中调用QWidget构造函数(我假设QWidgetQWidget_add_travel的超类)。 Because the superclass's constructor is not called, the data allocated on the heap for your widget is in an undefined state , ie sooner or later something breaks.由于未调用超类的构造函数,因此在堆上为您的小部件分配的数据处于未定义状态,即迟早会出现问题。

Here's a fixed version:这是一个固定版本:

QWidget_add_travel::QWidget_add_travel(QWidget *parent) 
        : QWidget(parent), via_l(new QVBoxLayout(this))
{
    build();
}

I also took the liberty of simplifying your layout construction by passing this to the layout constructor.我还通过了经过简化的布局结构的自由this布局构造。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM