何时不删除GTK +窗口指针?

时间:2018-03-27 03:29:58

标签: c++ gtk3

学习GTK +。查看教程中的这个(修改过的)示例:

#include <gtk/gtk.h>
int main(int argc, char *argv[])
{
    gtk_init(&argc, &argv);
    // create the window and remember it as a simple pointer
    GtkWidget *window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
    gtk_widget_show(window);
    gtk_main();
    return 0;
}

由于windownewgtk_window_new()'的指针,我认为我会做正确的事情并将其修改为这样(注意使用unique_ptr):

#include <memory>
#include <gtk/gtk.h>
int main(int argc, char *argv[])
{
    gtk_init(&argc, &argv);
    // create the window but this time store it as a smart pointer
    std::unique_ptr<GtkWidget> window(gtk_window_new (GTK_WINDOW_TOPLEVEL));
    g_signal_connect(window.get(), "destroy", G_CALLBACK(gtk_main_quit), NULL);
    gtk_widget_show(window.get());
    gtk_main();
    return 0;
}

但是,删除托管指针时会崩溃:

*** Error in `example': free(): invalid pointer: 0x00005620c8cfc510 ***
fish: “example” terminated by signal SIGABRT (Abort)

Valgrind确认免费电话是问题所在:

==00:00:00:21.223 17024== Invalid free() / delete / delete[] / realloc()
==00:00:00:21.223 17024==    at 0x4C3123B: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==00:00:00:21.223 17024==    by 0x10F240: std::default_delete<_GtkWidget>::operator()(_GtkWidget*) const (/usr/include/c++/7/bits/unique_ptr.h:78)
==00:00:00:21.223 17024==    by 0x10F6BE: std::unique_ptr<_GtkWidget, std::default_delete<_GtkWidget> >::~unique_ptr() (/usr/include/c++/7/bits/unique_ptr.h:268)

显然GTK +删除了窗口本身!?但是GTK +管理所有指针本身吗?或者只是顶级窗户?还是...?

请注意,gtk_window_new()的文档没有提到对象生存期管理,因此我对使用各种GTK +函数返回的指针做正确的事情感到困惑。  https://developer.gnome.org/gtk3/stable/GtkWindow.html#gtk-window-new

编辑:考虑更多 - 可能问题是由使用C ++ delete而不是C free()的std :: unique_ptr引起的?

0 个答案:

没有答案