2016-12-27 21 views
0

我想在构造函数中的类中分配一个GtkWidget指针,但是我遇到了运行时错误。GTK +:无法初始化GtkWidget *数据成员

#include <gtk/gtk.h> 

class MainWindowController 
{ 
private: 
    GtkWidget * appWindow; 
    const gchar * windowTitle = "Window title"; 
public: 
    MainWindowController(GtkApplication * app); 
    ~MainWindowController(); 
    void show(); 
}; 

MainWindowController::MainWindowController(GtkApplication* app) 
{ 
    //this works 
    GtkWidget* window = gtk_application_window_new(app); 

    //not this 
    //appWindow = gtk_application_window_new(app); 

    /*adding it into the init list does not work either... I have tried 
    MainWindowController::MainWindowController(GtkApplication* app) 
     :appWindow(gtk_application_window_new(app)) {} 
    */ 

    gtk_window_set_title(GTK_WINDOW(appWindow), windowTitle); 
    gtk_window_set_default_size(GTK_WINDOW(appWindow), 500, 500); 
} 

以下错误被报道在终端:

(main:156): GLib-GObject-WARNING **: instance with invalid (NULL) class pointer 
(main:156): GLib-GObject-CRITICAL **: g_signal_handlers_destroy: assertion 'G_TYPE_CHECK_INSTANCE (instance)' failed 
(main:156): GLib-GObject-WARNING **: instance with invalid (NULL) class pointer 
(main:156): GLib-GObject-CRITICAL **: g_signal_handlers_destroy: assertion 'G_TYPE_CHECK_INSTANCE (instance)' failed 

为什么没有这导致错误

GtkWidget* window = gtk_application_window_new(app); 

但这呢?

appWindow = gtk_application_window_new(app); 

更新:这是我的main.cpp

#include <gtk/gtk.h> 
#include "mainWindowController.hpp" 

static void 
activate (GtkApplication* app, 
      gpointer  user_data) 
{ 
    MainWindowController mainController(app); 
} 

int 
main (int argc, 
     char **argv) 
{ 
    GtkApplication *app; 
    int status; 

    app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE); 
    g_signal_connect (app, "activate", G_CALLBACK (activate), NULL); 
    status = g_application_run (G_APPLICATION (app), 0, 0); 
    g_object_unref (app); 

    return status; 
} 

我也跟编译:G ++ pkg-config --cflags gtk+-3.0 -o主要的main.cpp pkg-config --libs gtk+-3.0 -std =的C++ 0x

+0

我们需要查看更多代码。您发布的内容没有任何问题。 – andlabs

回答

2

你是没有显示完整的代码,但我认为问题是在这一行:

MainWindowController mainController(app); 

在这里你创造e MainWindowController类型的局部变量mainController,紧随其后,该变量因超出范围而被销毁。

现在,接下来会发生什么的细节取决于这个类的析构函数的作用。我猜你正在做的事情appWindow,使对象无效(gtk_widget_destroy()也许?)。或者,也许你试图在调用析构函数之后在信号中使用appWindow,这是未定义的行为。

+0

现货!是我的析构函数,我打电话给g_object_unref(appWindow) – JohnnyWineShirt