c ++多次将内存分配给同一个指针

时间:2013-05-16 21:47:08

标签: c++ qt pointers memory allocation

我正在处理一段代码,我不能100%确定它的正确性。请你告诉我你怎么看? (我在Qt编码)

只有一个样本:

CustomWidget *widget; //defined as private

widget = new CustomWidget(this);
connect(widget,SIGNAL(onCLose(), this, SLOT(onWidgetClose()));

widget = new CustomWidget(this);
connect(widget,SIGNAL(onCLose(), this, SLOT(onWidgetClose()));

widget = new CustomWidget(this);
connect(widget,SIGNAL(onCLose(), this, SLOT(onWidgetClose()));


void onWidgetClose(){
   CustomWidget *w = findClosedWidget();
   delete w;
}

1 个答案:

答案 0 :(得分:1)

没有必要编写自己的onWidgetClosefindClosedWidget - 特别是因为编写正确的findClosedWidget非常重要。而是使用专为此目的而设计的插槽QObject::deleteLater

CustomWidget *widget; //defined as private

widget = new CustomWidget(this);
connect(widget,SIGNAL(onCLose(), widget, SLOT(deleteLater()));

widget = new CustomWidget(this);
connect(widget,SIGNAL(onCLose(), widget, SLOT(deleteLater()));

widget = new CustomWidget(this);
connect(widget,SIGNAL(onCLose(), widget, SLOT(deleteLater()));