您的位置:首页 > 其它

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

2008-04-08 20:04 381 查看
先看一个简单的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()稍微安全一些吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: