View Full Version : Using Singletton Pattern for global variables
harmodrew
7th August 2010, 00:52
Hello you all!
I read about Singletton Pattern in this post:
http://www.qtcentre.org/threads/5326-Qt-and-global-variables
But if I'd like to use it to store a global variable (yes, I need it because I cannot pass it as an argument of function or other things like this) should I add only the variable in the class? as a static member?
Lykurg
7th August 2010, 05:06
Hi,
if you want to use the singleton patters use the last version from our wiki with the mutex locker. Then best practice is to add a local private variable and use a getter and setter function. Also a public static const default variable is useful if you store user settings with QSettings.
If you want to store a non changeable variable, i would just define a global variable without the singleton pattern.
Lykurg
harmodrew
7th August 2010, 09:21
and how should I declare and define a global variable? in one-file-projects you can declare a variable out of the main after the #include (it's so ugly but it's possible). for multi-file-projects where do I put global variable declaration?
tbscope
7th August 2010, 09:25
The most obvious things are the hardest to figure out. That's because we puny humans always think too far.
Just create a header file like mySuperDuperGlobalVariables.h
Then include the header where you need it.
Don't forget to include it once (use #ifndef, #define, ...)
harmodrew
7th August 2010, 09:31
Shall I add "static" to the variables so that all instances of them will edit the same phisical variable?
Lykurg
7th August 2010, 09:37
Just create a normal header file and include it in every file where you need that global variables. (Using namespaces is also a good choice to group your variables!)
#ifndef ARTISTICSTYLECONSTANTS_H
#define ARTISTICSTYLECONSTANTS_H
namespace ArtisticStyle
{
namespace Constants
{
// Predefined Style Options
const char* const ASP_STYLE = "style";
const int ASP_STYLE_DEF = -1;
// Tab and Bracket Options
const char* const ASP_INDENT = "indent";
const bool ASP_INDENT_DEF = true;
const char* const ASP_INDENTSTYLE = "indentStyle";
const char* const ASP_INDENTSTYLE_DEF = "spaces";
const char* const ASP_INDENTSIZE = "indentSize";
const int ASP_INDENTSIZE_DEF = 2;
const char* const ASP_BRACKETS = "brackets";
const bool ASP_BRACKETS_DEF = true;
const char* const ASP_BRACKETSSTYLE = "bracketsStyle";
const int ASP_BRACKETSSTYLE_DEF = astyle::BREAK_MODE;
// [...]
}
}
#endif // ARTISTICSTYLECONSTANTS_H
tbscope
7th August 2010, 09:37
static and editing very rarely go together in one sentence.
Except when pointing out that static is static and can't be edited.
static int myStaticInt = 5;
cout << "my static int =" << myStaticInt;
That's all you can do with a static variable.
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.