I'm trying to make a global settings provider for an application. It seemed bulky to have one object duplicated in so many different classes.
I've seeth this method work when the private static variable was something simple, like an integer, but I want it to work for QSettings—an object.
// settings.h
class Settings {
public:
static void Initialize();
static int serverRefreshRate();
private:
QSettings *settings;
};
// settings.cpp
#include "Server/settings.h"
void Settings::Initialize() {
Settings::settings = new QSettings(/* etc */);
}
int Settings::serverRefreshRate() {
return settings->value("server/refreshRate", 10000).toInt();
}
Is there a way I can achieve this, or am I going about it in the wrong way?
Thanks!
EDIT,
Firstly, it needed to be:
static QSettings *settings;
And I needed the following in the .cpp.
QSettings* Settings::settings = NULL;
Related
I've got the following MQL code:
class Collection {
public: void *Get(void *_object) { return NULL; }
};
class Timer {
protected:
string name;
uint start, end;
public:
void Timer(string _name = "") : name(_name) { };
void TimerStart() { start = GetTickCount(); }
void TimerStop() { end = GetTickCount(); }
};
class Profiler {
public:
static Collection *timers;
static ulong min_time;
void Profiler() { };
void ~Profiler() { Deinit(); };
static void Deinit() { delete Profiler::timers; };
};
// Initialize static global variables.
Collection *Profiler::timers = new Collection();
ulong Profiler::min_time = 1;
void main() {
// Define local variable.
static Timer *_timer = new Timer(__FUNCTION__); // This line doesn't.
//Timer *_timer = new Timer(__FUNCTION__); // This line works.
// Start a timer.
((Timer *) Profiler::timers.Get(_timer)).TimerStart();
/* Some code here. */
// Stop a timer.
((Timer *) Profiler::timers.Get(_timer)).TimerStop();
}
which defines a Timer class which is used as a timer to profile the functions how long it took. The original version uses a list of timers to store time separately on each call, however, the code has been simplified to provide a minimum working example and focus on the actual compilation problem.
The problem is when I'm using the following line in order to initialize a static variable:
static Timer *_timer = new Timer(__FUNCTION__); // Line 30.
the compilation fails with:
'Timer' - local variables cannot be used TestProfiler.mqh 30 30
When I drop static word, the code compiles fine.
But it doesn't help me, as I want to define this variable as a static pointer to the class, as I don't want to destroy my object each time when the same function is called over and over again, so the timers can be added to the list which can be read later on. I don't really see why the MQL compiler would prevent from compiling the above code. I also believe this syntax worked fine in the previous builds.
I'm using MetaEditor 5.00 build 1601 (May 2017).
What is wrong with my static variable declaration and how can I correct it, so it can point to a Timer class?
Keyword static has two different meanings in MQL4/5: it indicates that a member of a class is static (which is obvious), and it also says that a variable is static... for instance, if you have a variable that is used only in one function, you probably do not need to declare it globally but as a static. You can find an example of isNewBar() function that has static datetime lastBar=0; in the articles about new bar at mql5.com. This keyword in such a function says that the variable is not deleted after function is finished, but remains in memory and is used with the next call. And if you need a variable in OnTick() function - it does not make sence to have it static, declare it globally.
I need to write a custom appender in log4cxx. This answer describes how to do it. In Java, in log4j, it is possible for a custom appender to devise custom parameters. I add a property and a getter and setter:
private int myParameter = 0;
public void setMyParameter(int p) { myParameter = p; }
public int getMyParameter() { return myParameter; }
Then I can use myParameter in configuration file, and the framework somehow knows how to configure my appender with it.
Question: does log4cxx have a similar capability? For me it is enough if I get a map map<string, string> with properties.
Ok, figured out the answer myself. You need to override member function setOption. It will get called a number of times: once per each read option. You then override function activateOptions and its get called after all options have been processed. It can be used as a trigger to initialize the appender with the read parameters.
Not as convenient as mapping to getters/setters, but it gets the job done:
class CustomAppender : public AppenderSkeleton
{
int _myParameter = 0;
void initialize(int myParameter);
// ...
public:
void setOption(LogString const& option, LogString const& value) override
{
if (option == "MyParameter") try
{
_myParameter = boost::lexical_cast<int>(value);
}
catch (boost::bad_lexical_cast const&) {
// go with default
}
}
void activateOptions(helpers::Pool &) override
{
initialize(_myParameter);
}
};
I'm coding a business layer for an ASP.NET application. I've created database methods in my BLL as static. I've created public static Func variables to be compiled and used in several different methods, like this:
namespace BLL
public class User
{
public static Func<Context, variable, result> selectUser;
private static void CompileQuery()
{
if(selectUser == null)
{
selectUser = CompiledQuery.Compile......
}
}
public static UserClass Select(int id)
{
CompileQuery();
//uses selectUser
}
public static SomethingElse DoSomethingElse()
{
CompileQuery();
//also uses selectUser
}
}
It'll be used in ASP.NET layer like this:
using BLL;
private void AddUser()
{
UserClass user = User.Select(id);
}
My question is, since static variables are not thread-safe, is this a bad design decision? I'm thinking of either implementing a locking mechanism, which makes me think if it'd slow down the application, or using instantiated class approach which makes me wonder if query compiling would be beneficial. I'd appreciate any advice on this.
It should at least be read-only - and initialized on type load, like this:
public static readonly Func<Context, variable, result> selectUser =
CompileQuery(); // Or inline this...
private static Func<Context, variable, result> CompileQuery()
{
return CompiledQuery.Compile(...);
}
I'd probably make it a property myself, but otherwise it should be okay. Delegates themselves are immutable and threadsafe, so that shouldn't be a problem.
Doing it on type initialization means you don't need to worry about locking: the CLR guarantees that a type initializer is executed once and only once.
I have a function in a class file called auth_user and its in App_code folder.
I am trying to call that function from random pages that are on the website.
Inside the class file is a function that is simple, basicly check for flags in the sessions, i just wanna have it there so i dont have to type it again and again.
I want to be able to call it with one function like auth_user();
How would i do this excetly ?
would the function be public static void or what ?
Static makes sense for this:
public class AuthUtility
{
public static bool IsUserAuthorized()
{
....
return retVal;
}
{
And then you would call it:
AuthUtility.IsUserAuthorized();
Edit Based on Comments
So, not to be rude, but that information in your comments would've been pertinent in your original question and saved a fair amount of time.
Regardless, you'll need to pass in either the current HTTPContext or the Current Session into your static method:
public class AuthUtility
{
public static void AuthorizeUser(HttpSessionState currentSession)
{
currentSession["whatev"] = "rockin";
.....
}
}
And the you would call it:
AuthUtility.AuthorizeUser(this.Session);
I have two Cairngorm MVC Flex applications (a full version and lite version of the same app) that share many Classes. I have put these Classes into a Flex Library Project that compiles as an SWC. Both applications use some static String constants. Right now, I am storing these in the ModelLocator:
package model
{
[Bindable]
public class ModelLocator
{
public static var __instance:ModelLocator = null;
public static const SUCCESS:String = "success";
public static const FAILURE:String = "failure";
public static const RUNNING:String = "running";
...
}
}
This just doesn't seem like the best place to store these constants, especially now that they are used by both applications, and I have setup each application to have its own ModelLocator Class. Plus this is not the purpose of the ModelLocator Class.
What would be a good way to store these constants in my shared Library?
Should I just create a Class like this?:
package
{
[Bindable]
public class Constants
{
public static const SUCCESS:String = "success";
public static const FAILURE:String = "failure";
public static const RUNNING:String = "running";
}
}
and then reference it like this:
if (value == Constant.SUCCESS)
...
I'd say organize the constants by logical meaning, instead of a single Constants class.
Say you have the 3 you show as some kind of task state, and you have some more that are used as error codes for file access (just making stuff up here):
public class TaskStates {
public static const SUCCESS:String = "success";
public static const FAILURE:String = "failure";
public static const RUNNING:String = "running";
}
public class FileErrors {
public static const FILE_NOT_FOUND:String = "filenotfound";
public static const INVALID_FORMAT:String = "invalidformat";
public static const READ_ONLY:String = "readonly";
}
I find this makes it easier to document what the expected values are for something. Instead of saying "Returns either SUCCESS, FAILURE, RUNNING, ...", you can just say "Returns one of the TaskState.* values).
You could put all these in a single package for constants, or you could have the constant classes live in the same package as the classes that use them.