【问题标题】:c++ multiple times memory allocation to the same pointer [closed]c ++多次内存分配给同一个指针[关闭]
【发布时间】:2013-05-16 21:47:08
【问题描述】:

我正在处理一段代码,但我不能 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;
}

【问题讨论】:

标签: c++ qt pointers memory allocation


【解决方案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()));

【讨论】:

  • 谢谢,是的,在我的真实代码中,我正在使用 deleteLater。我最好奇的是 new CustomWidget 多次分配给我的私有指针。这干净正确吗?
  • @MiroKarpis 是的,就我个人而言,我也不太喜欢这种风格,但我遇到过这种情况(像这种情况),这是最容易做的事情。事实是,这不可能是您的代码的全部内容,对吧?每个widget 分配都有自己的特点。所以实际上我会给他们每个人自己的名字和单独的声明。尽管所写的内容是完全合法的,但只要调用代码具有访问权限,即是包含 widget 的类的成员函数或朋友。
  • 非常感谢 - 这就是我所追求的。
  • 或者只是小部件->setAttribute(Qt::WA_DeleteOnClose);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
  • 2016-02-21
  • 1970-01-01
  • 2011-03-19
  • 2020-12-16
相关资源
最近更新 更多