Warning, /multimedia/amarok/HACKING/static_variables.txt is written in an unsupported language. File is not indexed.
0001 Preface: 0002 ====== 0003 You've probably noticed the epic struggle we've had with Amarok 2 0004 hanging on exit. After _months_ of tinkering I've now been able to 0005 identify and fix this issue. This document explains how to prevent 0006 such issues in the future. 0007 0008 What is a static object? 0009 ================= 0010 A static object is being initialized on program start, and will only 0011 become instantiated once. It's conveniently used with the singleton 0012 design pattern, e.g. in Amarok code. 0013 0014 Example: 0015 0016 static AmarokMenu s_menu; 0017 0018 What is so dangerous about static objects? 0019 ================================ 0020 A static object's destructor is called _after_ the QApplication 0021 destructor has been executed. This is fine for plain old datatypes 0022 (POD) like int, float, and pointers, as they do not have a destructor. 0023 It's also fine for objects with a trivial destructor that does not 0024 interfere with the rest of the program. 0025 0026 The danger lies in using static objects that call other parts of the 0027 application in their destructor. This is e.g. true for most QObjects, 0028 which rely on the QApplication being intact. If the QApplication is 0029 destroyed before the static QObject's destructor is run, _bad_ things 0030 can happen. To name a few: Crashing, hanging, eating live kitten, or 0031 forcing you to use XMMS. 0032 0033 How can I prevent these problems? 0034 ========================== 0035 Use K_GLOBAL_STATIC, and use qAddPostRoutine() to ensure that the 0036 static object's destructor is called when QCoreApplication destructs. 0037 0038 Example: 0039 0040 class AmarokMenu : public QMenu 0041 { 0042 AmarokMenu(); 0043 }; 0044 K_GLOBAL_STATIC( AmarokMenu, s_menu ) 0045 0046 AmarokMenu::AmarokMenu() 0047 { 0048 // K_GLOBAL_STATIC is cleaned up *after* Q(Core)Application is gone 0049 // but we have to cleanup before -> use qAddPostRoutine 0050 qAddPostRoutine( s_menu.destroy ); 0051 } 0052 0053 Further reading: 0054 =========== 0055 http://api.kde.org/4.0-api/kdelibs-apidocs/kdecore/html/group__KDEMacros.html 0056 0057 0058 Thanks for reading, and happy hacking :)