Safety using entity from different part of program - c++

I have several modules in my program (e.g. Database, Scheduler) which uses same entity - some game server.
Main goal is that each module uses game server API with limited functionality (functionality which need for interaction between separate module and game server only) and other functions must be hide.
I have created such functionality. But I don't now, maybe it's wrong realization or maybe somebody guess better method.
Class which placed below contain some operations which can be access only from others modules via classes wrappers.
#ifndef _GAMESERVER_
#define _GAMESERVER_
#include <vector>
class GameServer
{
static GameServer instance;
std::vector<int> game_actions;
GameServer(){}
~GameServer(){}
GameServer(const GameServer&){}
protected:
void addGameAction(int action) // Some functionality, which can be accessible only from others modules via classes wrapers
{
game_actions.push_back(action);
}
public:
static GameServer *getInstance()
{
return &instance;
}
bool start()
{
return true;
}
void stop()
{
}
};
#endif
Below placed class 'wrapper' for class GameServer which has been realising API for interaction with module Database.
#ifndef _DBGAMESERVER_
#define _DBGAMESERVER_
/* Database module will use this API for interacting with game server */
class GameServer;
class DBGameServer : protected GameServer
{
DBGameServer();
public:
static DBGameServer *getInstance()
{
return static_cast<DBGameServer *>(GameServer::getInstance());
}
void addGameAction(int action)
{
GameServer::addGameAction(action);
}
};
#endif
Thanks!

You are creating your singleton instance at first call to getIntance. It may be unsafe in a multithreaded application : race conditions could lead to multiple instances being actually intialized and used.
IMHO you would better use static initialization :
Declaration :
...
class GameServer {
static GameServer& instance;
// private constructor, copie constructor and destructor
...
public:
static GameServer * getInstance() { return &instance; }
...
}
Implementation :
...
GameServer & GameServer::instance = GameServer();
...
That way you are sure that the object is constructed only once during program start (before first instruction), and destructor is called at program end (after last instruction). Of course if constructor throws an exception the program will stop abruptly before it is given any chance to display anything : the eventual error messages should be displayed inside constructor.

Related

How can I fix and/or re-design this event class system to not require exclusively public data members?

I have an Event system in which a Manager class contains a queue of Events. The Event class is currently an abstract base class from which all specific events are derived. The idea is to allow the Manager to process() specific events that are specialized classes constructed with their own, unique parameters elsewhere in the code where the context of creation informs which event to create and how (sometimes using an Abstract Factory pattern). These Events are consumed asynchronously by Manager in a loop that continuously empties the queue, processing each event, and then destroying it as it is popped.
I designed this system to alleviate Manager from doing all of its own data manipulation. Instead, other parts of the code can queue an Event object, and that object can perform a task via its process() member, with the Manager not needing to know about it in detail.
Without an encapsulated Event system, I would be making endless additions to Manager's members: one for each task, and calling those tasks in case statements somewhere, which is terrible. I thought it would be better to use the Event system I have in the example here. This leaves Manager unchanged while various derived, specific events are defined elsewhere. This minimal example works fine, but the problem is that all derived Events need access to Manager's private data for each one's process() to have full capability as intended. If friend inheritance was allowed, simply making Event a friend class of Manager would solve the problem. Since it's not, the only way for this to work is to make all of Manager's data public (or, technically, add every new derived Event class I make as a friend to Manager).
This works, but feels wrong, and makes me think this is not the correct design. To be clear, the Manager contains a good deal of centralized information (necessary for thread sync, etc) that is more extensive than the Example would indicate. It manages network connections that will spawn a variety of different, often arbitrary events. I'd like to elegantly react to such an environment without inflating Manager with endless additional member functions every time I want to create a new type of event.
Is there a better way to achieve this code separation pattern and still retain the freedom I want for the separated code? Should I just publicize all of Manager's data after all?
The minimal Example (includes pseudocode):
class Event;
class Manager
{
public:
Manager() {}
// Event queue insertion and processing functions omitted
// private: // Commented out on purpose to allow compilation
int dataInt;
double dataReal;
std::string dataStr;
std::queue<Event *> events;
};
// Abstract Event base class with process() member
class Event
{
public:
Event(Manager * m) : manager(m)
{
process = std::bind(&Event::processKernel, this);
}
// Process the event
std::function<void(void)> process;
protected:
// Actual processing code: derived classes must define this function
virtual void processKernel() = 0;
private:
Manager * m;
};
// One example of a specialized (derived) Event
class SpecificEvent: public Event
{
public:
SpecificEvent(Manager * m, int p) : Event(m), param(p) { }
void processKernel()
{
// Intention: modify parent manager data
manager->dataInt = param;
}
private:
int param;
};
// Another specialized (derived) Event
class OtherEvent: public Event
{
public:
OtherEvent(Manager * m, double p) : Event(m), param(p) { }
void processKernel()
{
// Intention: modify parent manager data
manager->dataReal = param;
}
private:
double param;
};
// Example usage: could be inside a Manager member, or anywhere else
int main()
{
Manager manager;
// Make a SpecificEvent, pass it the manager, and its own specific parameter(s)
SpecificEvent e(&manager, 10);
//<Not shown> Add to manager's queue
// Manager processes this event at some point later with Event::process()
}
Since
If friend inheritance was allowed, simply making Event a friend class
of Manager would solve the problem
you can just get away with
struct ManagerFields { // all Manager's fields; just for the further convenience
int dataInt;
double dataReal;
};
class Manager: private ManagerFields { // only Manager and its friends know these Fields
friend class Event;
// here Manager can use dataInt, dataReal etc. just like before
};
class Event {
public:
Event(Manager* m) : manager{m} {}
virtual void process() = 0;
protected: // "friend inheritance" setup below
ManagerFields& fields() { return *manager; } // "the further convenience"
private:
Manager* manager;
};
class SpecificEvent: public Event {
public:
SpecificEvent(Manager* m, int p) : Event{m}, param{p} {}
void process() override { fields().dataInt = param; } // "friend inheritance" usage
private:
int param;
};
See the comments in the code.

C++ class design with polymorphism

I am doing some networking stuff, but the question is not related to networking. I have a generic network event handler, where I can register an network connection ("NwConnection" class) and idea is whenever a message arrives on the connection, it will call me back.
class NwEventManager {
public:
using CallBack = std::function<void(std::shared_ptr<NwConnection>)>;
registerCallback(
std::shared_ptr<NwConnection> con,
CallBack rdCallback,
CallBack errorCallBack);
};
So the application will create a NwConnection and register with Event Manager.
(NwConnection is an abstract class, which internally can be a TCP/Unix domain socket etc.)
Anyway, I need to keep some per-connection information, say some statisctics.
Currently what I am doing is:
class TcpNwConnection : public NwConnection {...}
class MyNwConnection : public TcpNwConnection {
using NwConnection::NwConnection;
....
MyStatistics& getStats ()
{
return myStats_;
}
private:
MyStatistics myStats_;
};
And in the callback, which will call me back with the NwConnection Abstract class I static cast the pointer to my type and access the stats.
// read callback
[] (std::shared_ptr<NwConnection> con)
{
auto myConn = static_cast<MyNwConnection *>(con.get());
auto& stats = myConn->getStats();
}
Is this a good approach?
Obviously the problem is, if my code has to be independant of the NwConnection type, say I want to deal with TcpConnection and UnixConnection, I cannot follow this approach (unless I do with templates).
One solution is to re-write things with connection type inside the NwConnection:
class TcpStream : public AbstractStream {}
class UnixStream : public AbstractStream {}
class NwConnection {
Message read (...)
{
return stream->read(...);
}
private:
AbstractStream *stream;
};
Now I can do my static_cast and the type of connection doesnt matter.
But what is a better way to design this thing, while allowing applications to keep the per-connection data? (I am free to rewrite any part of the code.)

What kind of class structure do I need?

I just needed something like this:
I have got a robot class which contains a motor object and a predefined callback function (which is triggered on an interrupt).
robot.h
class robot
{
public:
motor motor1;
};
motor.h
class motor
{
public:
int incrementPosition();
int getPosition();
private:
int position;
};
callback.cpp
void callback(){
motor1.incrementPosition(); //callback function needs to reach this already created motor1
}
What I am trying to achive is:
Robot and motor objects has to be created only once (only one robot and one motor are allowable, bacause it is connected to a real physical robot and a motor),
Motor object (motor1) has to be created automatically and most importantly, it should be callable from the prefined callback function.
So the main should be like this,
main(){
robot myRobot;
robot myRobot2; //is not allowed or should be useless
printf("%d\n", myRobot.motor1.getPosition());
}
Not that I really like to recommend that1, but obviously the Singleton Pattern comes to mind:
class robot {
robot() {}
public:
motor motor1;
static robot& instance() {
static robot theRobot;
return theRobot;
}
};
The only way to access an instance of robot is to use the instance() function then.
main(){
robot myRobot; // Fails to compile since the constructor is private
printf("%d\n", robot::instance().motor1.getPosition());
// ^^^^^^^^^^^^^^^^^ Access the one and only instance
}
The same way the single motor instance can be accessed in the callback function:
void callback(){
robot::instance().motor1.incrementPosition();
}
Some more considerations:
Make your robot class implement an interface like
struct IRobot {
virtual ~IRobot() {}
virtual std::vector<std::shared_ptr<IMotor>>& motors() = 0;
};
this makes it easier to write isolated unit tests and mock the robot singleton.
Instead of the static instance() function provide a global access function for the singleton instance that returns the above mentioned interface. This also can be easier replaced with a function that returns a mock object for unit testing.
1)The Singleton Design Pattern is often blamed as a bad design, and in most cases it actually is a bad decision. Nevertheless there are valid use cases, especially when designing embedded systems. You have one single and autonomous robot, that's clear and deserves a singleton.
It's considerable though, if you should fix yourself to a single motor from the beginning, it would be hard to change if the HW engineers decide to need a second motor.

Setup static member object

Maybe this question has been asked around but I couldn't find it. How do I setup a static member object at its creation? And possibly perform some other tasks. The goal is to have some of it's setters called at it's creation time.
Example:
Header file A.h:
class A{
public:
A::A();
~A::A();
static QTimer updateTimer;
};
Expected implementation file A.cpp:
#include "A.h"
QTimer A::updateTimer.setInverval(100); // I need to set it's inverval to 100ms
// but only once in the beginning of it's life time
A::A(){...
}
~A::A(){...
}
So, as you can see, I would like to call 'setInverval()' function of my static object only once at it's creation and not have it called every time a new 'A' object is created.
This is what constructors are for.
If it's your own type, just write a constructor.
If the type doesn't have a constructor and you cannot modify it (like, presumably QTimer comes from Qt), then wrap it in a type of your own that does. This is a textbook case of inheritance being useful. Your wrapper class will extend the original class with a bit of new functionality: setting the interval during initialisation.
struct QTimerWrapper : QTimer
{
QTimerWrapper(int interval)
{
setInterval(interval);
}
};
struct A
{
static QTimerWrapper updateTimer;
};
QTimerWrapper A::updateTimer(100);
Or you could use composition, having the QTimer be a member of QTimerWrapper instead.
In addition to composition or inheritance, you can also create a function which returns the modified object
QTimer newTimerWithInterval(int interval){
QTimer timer;
timer.setInteval(interval);
return timer;
}
QTimer A::updateTimer(newTimerWithInterval(100));
You might want to put the function under local namespace as you do not probably need it anywhere else.
maybe something like this? pseudocode:
class A { static shared_ptr<Timer> _timer; };
..
A::A()
{
if (_timer == nullptr)
{
_timer.assign(new Timer);
_timer->setInterval(100);
}
}
or if you don't need to manage this timer or have any dynamic objects - then you can use statically made inner object:
class A { /* without static member */ };
A::A
{
static bool timerInited = false;
static QTimer timer;
if (!timerInited)
{
timer.setInterval(100);
timerInited = true;
}
}

Multithreading Design, protect global member in C++

I am writing a c++ app with QT, with a focus at speed optimization.
I want to have a few global objects with read only access for different threads.
Before I open the threads, I have to initialize the global objects and fill them with data.
How I can protect the set functions of my Global Objects, but still have access from the main function?
Example code like it is now:
myClass.h
class MyObjectClass {
public:
void SetSome(const QList<QString> &value);
QList<QString> GetSome() const;
private:
QList<QString> m_myMember;
};
main.cpp
#include "global.h" // some like: extern MyObjectClass g_InihalizedInMain;
#include "anyThread.h"
int main(){
g_InitializedInMain.SetSome() // This Shut work
MyThread thread;
thread.start();
//..
return 0;
}
anyThread.cpp:
#include "global.h"
void thread::run()
{
MyObjectClass newObject = g_InihalizedInMain; //This shut work
g_InitializedInMain.GetSome(); //This shut work
g_InitializedInMain.SetSome(); //This shut not work and give me an error during compile time
newObject.SetSome(); //This shut work
}
I would be happy if you have a few design ideas for me, thanks a lot!
class MyPrivateObjectClass : private MyObjectClass
{
public:
friend void main();
};
extern MyPrivateObjectClass g_InitializedInMain;
Make your global variable static which means only the one source file can access it. You can then provide accessor functions that can read the data from other threads.
For starters, I would try to avoid global variables at all costs.
What you could do instead of global variables is to instantiate a variable in main (either
dynamically, or locally on the stack, depending on your preferences)
and set it in the thread object (this is called dependency injection)
To control setting attributes on MyObjectClass only from main, I can think of 2 options:
Set all of the MyObjectClass attributes via the constructor in main, thus allowing you to remove the setters, but leave the getters. The MyObjectClass would be immutable.
Create a context object that contains all the settable attributes for MyObjectClass. This context object can only be passed into the MyObjectClass constructor. The context object should be created in main, calling the appropriate setters, then passed into MyObjectClass upon instantiation from main. The MyObjectClass class uses these attributes from the context object internally, but doesnt have setters for them. There would of course be getters available on MyObjectClass, that would get the values from the internal context object. The MyObjectClass would be immutable, but this way is a bit more flexible.
I prefer the second option. Here is a code sample:
myClass.h
class MyObjectContext {
public:
void SetSome(const QList<QString> &value);
QList<QString> GetSome() const;
private:
QList<QString> m_myMember;
};
class MyObjectClass {
public:
MyObjectClass(MyObjectContext *context) : context_(context) {}
QList<QString> GetSome() const {return context_->GetSome();}
// Put the rest of the important stuff here
private:
MyObjectContext *context_;
MyObjectClass(); // explicitly stating that the default ctor cant be called
};
main.cpp
int main(){
// creating these objects on the stack, you may need
// to create them dynamically, its up to you
MyObjectContext context;
context.SetSome() // This Should work
MyObjectClass moc(&context);
MyThread thread(&moc);
thread.start();
//..
return 0;
}
anyThread.h
class MyThread : public QThread { // Assuming you're inheriting from QThread
public:
// instead of setting it via the ctor, you could consider adding a setter
MyThread(MyObjectClass *moc) : moc_(moc) {}
void run();
private:
MyThread(); // explicitly stating that the default ctor cant be called
MyObjecctClass *moc_
};
anyThread.cpp
void MyThread::run()
{
moc_->GetSome(); //This should work
// Dont have to worry about the setters, since there are none
// available for the MyObjectClass, which is now immutable
}