[SOLVED] QTextEdit + Singleton = Memleak?



  • I am using Qt 4.8.4 and if I make a singleton out of a QMainWindow and assign a QTextEdit, I get a huge memory leak. Any ideas?

    @class Window : public QMainWindow
    {
    Q_OBJECT

    private:
    Window()
    {
    QTextEdit* textEdit = new QTextEdit(this);
    this->setCentralWidget(textEdit);
    textEdit->setPlainText(
    "\n"
    " INITIALIZING\n"
    "\n"
    " ~-_ Steamin'\n"
    " -~ Hot\n"
    " c|
    | COFFEE\n"
    "");
    }

    public:
    static Window* instance()
    {
    static Window instance;
    return &instance;
    }
    };@

    EDIT
    Found a way to solve it! If I swap my lazy singleton to an ordinary singleton, things will work out.
    @Window* instance()
    {
    // NOTE: "s_instance" is a static member variable
    if(!s_instance)
    s_instance = new Window();

    return s_instance;
    }@



  • How do you know you get a huge memory leak? (Do you mean on termination of your program? Technically that's not a memory leak, more of a moral thing...)



  • I tested it with Qt 5.0.2 as well, same result.

    [quote author="DerManu" date="1368224963"](Do you mean on termination of your program?)[/quote] Yes during termination. Still feels quite bad thought.

    My main looks like this:
    @int main(int argc, char *argv[])
    {
    // Detect memory leaks
    #if defined(DEBUG) | defined(_DEBUG)
    _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
    #endif

    // Create window
    QApplication a(argc, argv);
    Window* w = Window::instance();
    w->show();
    
    return a.exec();
    

    }@

    Haven't counted, but the memleak seems rather huge.
    !http://i.imgur.com/gEnd0Tb.png(Memory leak QTextEdit.)!



  • [quote author="Adelost" date="1368225736"]Yes during termination. Still feels quite bad thought.[/quote] Yes, you should feel a little dirty, that's okay.

    Just a guess: Delete the singleton memory in a controlled fashion before QApplication goes out of scope. Or try hard to get rid of the singleton, in case you haven't done that yet.



  • QTextEdit really doesn't like singletons it seems. Even if I delete the Widget manually still memleak. Gives me the creeps.
    @Window()
    {
    QTextEdit* textEdit = new QTextEdit();
    delete textEdit; // Deletes widget

    // Still memleak, hmm...
    }@

    The only widget affected so far seem to be QTextEdit and QPlainTextEdit, ordinary widgets seems to work fine.



  • Found a way to solve it! If I swap my lazy singleton to an ordinary singleton, things will work out.

    @Window* instance()
    {
    if(!s_instance)
    s_instance = new Window();

    return s_instance;
    }@


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.