-
Notifications
You must be signed in to change notification settings - Fork 63
Memory management
This section explains how memory management with SFGUI objects works.
Usually, in a lot of libraries and your own programs, you can choose how to manage objects in memory, for example by storing plain objects, using pointers, reference-counted pointers and many more.
When working with SFGUI, you have to use shared pointers most of the time — however this only counts for SFGUI's own objects. Of course, you don't have to apply that behavior to your own program.
A shared pointer works similar to a normal C++ pointer. The difference is that the memory a shared pointer references to is kept until all references to it get lost.
Here's a short example:
#include
int main() {
std::shared_ptr a_reference( new int );
{
std::shared_ptr another_reference( a_reference );
}
return 0;
}
Line 4 creates a new int and saves the address to it in a_reference
, a
shared pointer. Line 7 creates another shared pointer and initializes it to
point to the same address a_reference
points, too. At this point, the int
is referenced by two shared pointers
!
Line 8 ends the scope where another_reference
is valid. That means after line
8, the pointer will be dropped, and the amount of references to the integer
will be 1.
When the program ends after line 10, a_reference
is destroyed. From there
on, there's not a single reference to the integer anymore. Therefore it's
destroyed.
This is just a simple example. Please read more about shared pointers
here — take note of
std::make_shared
as well.
All SFGUI widgets are shared objects, without exceptions.
Shared objects have a special meaning, which is different from a shared pointer: SFGUI forces the user to use shared pointers to widgets. You are not allowed to create plain widget objects, never.
This won't work:
sfg::Button my_button( "Hello" );
Use this instead:
auto my_button = sfg::Button::Create( "Hello" );
The fact that all SFGUI widgets are shared objects allows you to totally forget about memory management for them. As soon as a widget isn't used anymore in your program, it will be deleted. If it's used, it'll be kept. It's that simple.
There are a couple of ways that allow to hold references to SFGUI widgets in a non-shared fashion. For example the following bad example works without problems:
sfg::Button::Ptr my_button = sfg::Button::Create( "Hello" ); // Good!
sfg::Button* button_ptr = &(*my_button); // NO-NO!
sfg::Button& button_ref = *my_button; // NO-NO!
DO NOT store raw pointers and/or C++ references to SFGUI widgets! The objects may become invalid at any time, which you can't control because raw pointers and references are invisible to the shared pointer mechanisms.