qtbad-alloc

How Qt handle bad allocation?


What if hypothetically the system ran out of memory and memory allocation failed.

We have a custom widget.

// win.h
class Win : public QWidget
{
    Q_OBJECT

public:
    Win(QWidget *parent = nullptr);
    ~Win();
protected:
    QLabel *label1,*label2;
    Counter *edit1,*edit2;
    QPushButton *calcbutton;
    QPushButton *exitbutton;
};

and imagine that in constructor memory allocation failed

Win::Win(QWidget *parent)
    : QWidget(parent)
{
    label1 = new QLabel("Some label 1", this); // for example this fails
    label2 = new QLabel("Some lable 2", this); // or this one

    QHBoxLayout *layout1 = new QHBoxLayout(this); // or this
    layout1->addWidget(label1);
    layout1->addWidget(label2);
}

And the question is How does qt handle it?


Solution

  • This is not Qt specific: the new expression will throw an instance of std::bad_alloc if it fails to allocate the storage.