关于Gtkmm窗口指针的delete 以及窗口的hide()方法和destroy_()方法

本文通过一个简单的Gtkmm示例,探讨了窗口指针删除以及窗口hide()和destroy_()方法的区别。在双指针删除窗口时,发现第二次delete操作会导致程序崩溃,这可能与Gtkmm的内部管理有关。此外,hide()方法仅隐藏窗口,允许程序继续执行,而destroy_()则会终止窗口及其关联的事件处理,导致后续代码无法正常执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看一个简单的Gtkmm的例子,问题在下面说:
===============HelloWorld.h===============
#ifndef HELLOWORLD_H_
#define HELLOWORLD_H_
#include <gtkmm.h>
class HelloWorld : public Gtk::Window
{
public:
  HelloWorld();
  virtual ~HelloWorld();
protected:
  virtual void on_button_clicked();  //Signal handlers:
  Gtk::Button m_button;  //Member widgets:
};
#endif /*HELLOWORLD_H_*/

===============HelloWorld.cpp===============
#include "HelloWorld.h"
#include <iostream>

HelloWorld::HelloWorld()
: m_button("Hello World")   // creates a new button with the label "Hello World".
{
  set_border_width(10); // Sets the border width of the window.
  m_button.signal_clicked().connect(sigc::mem_fun(*this, &HelloWorld::on_button_clicked));  // When the button receives the "clicked" signal, it will call the on_button_clicked() method. The on_button_clicked() method is defined below.
  add(m_button);  // This packs the button into the Window (a container).
  m_button.show();  // The final step is to display this newly created widget...
}

HelloWorld::~HelloWorld()
{
}

void HelloWorld::on_button_clicked()
{
  std::cout << "Hello World" << std::endl;
  this->hide();  //  this->destroy_();  <<------------
}

===============main.cpp===============
#include <gtkmm.h>
#include "HelloWorld.h"
#include <istream.h>

int main (int argc, char *argv[])
{
  Gtk::Main kit(argc, argv);

  HelloWorld* pHelloworld = new HelloWorld();
  HelloWorld* p2;
  p2 = pHelloworld;

  Gtk::Main::run(*pHelloworld); //Shows the window and returns when it is closed.

  delete pHelloworld;
  /*delete p2;*/    <<------------
  std::cout<<"Bye Bye!"<<std::endl;
  return 0;
}

通过以上的代码主要要说明两个问题: 1.Gtkmm窗口指针的delete 2.窗口的hide()方法和destroy_()方法的区别
(1) 在main函数中如果同时用两个指针指向new出来的窗口,那么当用delete释放空间没有任何问题,和标准C++一样。但是问题出在如果继续用delete 释放p2时程序就会崩溃(我注掉的部分)。这和标准C++书里的描述可不怎么一致了,现在还没有搞明白为什么会这样,大概是Gtkmm的问题吧。
(2) 窗口的hide()方法和destroy_()方法。注意到HelloWorld.cpp的void HelloWorld::on_button_clicked()中的注释么?如果使用this->hide()隐藏窗口,那么main.cpp中的"Bye Bye!"就可以输出来。但如果使用this->destroy_(),那你只会得到on_button_clicked()中输出的"Hello World",没人和你说"Bye Bye!"了。很奇怪,感觉像是连main()方法一起被destroy了一样。上网找资料也没有什么说法,所以我感觉还是hide()稍微安全一些吧。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值