I guess my question is stupid, but nevertheless:
In my C++ code I use some legacy C library(XLib). In order to use this library a connection to X server has to be opened first:
::Display* const display = ::XOpenDisplay(nullptr);
This display structure is widely used across the vast majority of the XLib functions, including the functions for allocating and freeing memory and system resources such as fonts, colormaps etc. In my code I use objects' constructors and destructors to allocate and free resources by calling these functions. And here is the problem:
int main()
{
::Display* const display = ::XOpenDisplay(nullptr);
// ...
Object1 object1(display, ...); // uses display inside the destructor
Object2 object2(display, ...); // uses display inside the destructor
Object3 object3(display, ...); // uses display inside the destructor
// ...
::XCloseDisplay(display); // invalidates the display structure
return 0;
}
This example leads to segmentation fault, because the display structure had been invalidated by XCloseDisplay() before any of the destructors using it was called. To avoid this issue I can embrace all the code before XCloseDisplay() in curly braces to limit the scope of objects, but it makes the code to be shifted to right which looks pretty ugly.
Is there any way to somehow call XCloseDisplay() after the main()?