Re: Newbie: question about destruction of FLTK ojbects
"'Albrecht Schlosser' via fltk.general"
12:40 Sep 27
On 9/27/26 12:16 S ET wrote:
Hello,
This is my very first step with FLTK and there are certainly many
basic things I'm missing about this library.
Welcome to the FLTK world!
My
concern here is about object destruction.
OK.
The
following mockup is created with FLUID. I have a added a
destructor that is not called at all when the double window
closes, with an exit code of 0.
[example code elided]
On application exit, nothing is printed in stdout and the
created directory persists. I would have expected the contrary.
I wish to know what's going on, how far is it normal and what
should I consider to resolve this.
Good.
Using fltk 1.4.5-2 on Arch Linux.
Thank you for any guidance.
FLTK does not delete any widgets by itself, unless they are stack
(local) or static objects, but such objects are destroyed by the
system (not the library itself) when they go out of scope. All
objects created by `new` are kept until exit of the program where
their memory is cleaned up by the system (you don't need to care),
but they are not `deleted`. This is normal C++ and intentional.
You would only delete FLTK widgets explicitly if they hold resources
you need to free at program exit, such as the file opened by your
window, or if you frequently add / delete widgets during execution
of your program.
The straigt-forward way to do what you want to achieve is to delete
the window right after Fl::run(), like this modified code:
// ... code like before ...
cw->show();
int ret = Fl::run();
delete ui;
return ret;
}
A better approach would IMHO be to allocate the `ui` instance on the
stack so it gets deleted automatically by the system after
Fl::run(). Then the destructor of the `ui` can do whatever it needs
(as you already wrote in your code).
// cat main.cpp
#include"blank.h"
intmain(intargc, char*argv[])
{
UserInterfaceui; // note: local (stack) variable
Fl_Double_Window*cw = ui.make_window();
cw->show();
returnFl::run();
}
This works as expected (tested by me).
Note that smart pointers (as Daniel G. suggested) would be another
way.
Note also that FLTK *does* automatically delete all *children*
of windows (groups) when the window (group) itself is deleted.
Last note: when you close the window by its close button, this calls
a callback you may define. If you don't define a callback for the
window (as in your code), then the standard callback is to hide (but
not delete) the window. Defining a callback for the window would be
yet another way to close the file, but I'm not going to post code
for this. Feel free to ask if you need more example code.
Comments are owned by the poster. All other content is copyright 1998-2026 by Bill Spitzak and others. This project is hosted by The FLTK Team. Please report site problems to 'erco@seriss.com'.