【发布时间】:2020-08-27 12:59:32
【问题描述】:
我在 GNOME Builder 上创建了一个示例 GTKMM 项目。最棒的是,为我的示例项目自动生成了一个示例 hello world 代码。由于 C++ 源文件被组织成三个部分:
- 头文件
- 实施文件
- 主文件
我已在单个 cpp 文件中修改了我的示例代码以进行演示:
#include <iostream>
#include <gtkmm.h>
using std::cout;
using Gtk::Application;
using Gtk::Window;
using Gtk::Box;
using Gtk::Button;
using Gtk::Label;
class HelloWindow : public Window
{
Box box;
Button button;
Label label;
public:
HelloWindow();
~HelloWindow();
};
HelloWindow::HelloWindow()
: Glib::ObjectBase("HelloWindow")
, Window()
, box(Gtk::ORIENTATION_VERTICAL)
, button("Clickable button")
, label("Hello World!")
{
set_default_size(320, 240);
bool expand(true), fill(true);
box.pack_start(label, expand, fill);
box.pack_end(button, expand, fill);
add(box);
show_all();
}
HelloWindow::~HelloWindow()
{
cout << "Object successfully destructed!\n";
}
static void
on_activate(Glib::RefPtr<Application> app)
{
Window *window = app->get_active_window();
if (not window) {
window = new HelloWindow();
window->set_application(app);
app->add_window(*window);
}
window->present();
}
int main()
{
auto app = Application::create("io.test.window-state-event");
app->signal_activate().connect(sigc::bind(&on_activate, app));
return app->run();
}
关于上述代码的一个有趣的部分是app 连接到on_activate 信号,这意味着用户只能运行该程序的一个实例。如果他尝试运行另一个实例,则会显示之前仍在运行的窗口。
但是,on_activate() 上使用了 new 关键字,这让我有点困惑。当用户关闭 HelloWorld 窗口时,对象真的被删除了吗?我对 C++ new 关键字的了解是,必须记住 delete 使用前一个关键字分配的任何对象。
此外,析构函数消息“对象已成功销毁!”关闭窗口时不打印。
【问题讨论】: