Singleton in my C++ program - c++

I wrote 2 classes, Agent and Timing. The third class will contain the main() function and manage it all. The goal is to create n instances of Agent and a SINGLE instance of Timing. It's important to mention that Agent uses Timing fields and Timing uses Agent functions.
How can I turn Timing to singleton?
//Agent.h
#ifndef Timing_h
#define Timing_h
#include <string>
#include "Timing.h"
class Agent{
public:
Agent(std::string agentName);
void SetNextAgent(Agent* nextAgent);
Agent* GetNextAgent();
void SendMessage();
void RecieveMessage(double val);
// static Timing runTime;
What I thought would solve my problem but I got:
'Timing' does not name a type
~Agent();
private:
std::string _agentName;
double _pID;
double _mID;
Agent* _nextAgent;
};
#endif
//Timing.h
#ifndef Timing_h
#define Timing_h
class Timing{
private:
typedef struct Message{
Agent* _agent;
double _id;
}Message;
typedef Message* MessageP;
Message** _messageArr;
static int _messagesCount;
public:
Timing();
void AddMessage(Agent* agent, double id);
void LeaderElected(string name);
void RunTillWinnerElected();
~Timing();
};
#endif
Is this really the way to create a singleton and if it is what is the problem?
And if not, how can I turn it to a singleton?

This bit looks suspicious in Agent.h ...
#ifndef Timing_h
#define Timing_h
Seems like it's the same define-guard in Timing.h. Therefore Timing will not be included in Agent.
Change it to
#ifndef Agent_h
#define Agent_h

Nope, the wikipedia page on the singleton pattern has a good example as well as a nice write up of how a singleton is actually constructed.

Your Timing is not a singleton. Multiple objects can be created. Singleton's typically rely on a static method and a private ctor and no copy ctor or op=. You have two choices:
Either create a static member Timing for Agent
Or, create a Timing& member for Agent and convert Timing to a proper singleton
Depending on your design, if the Timing object is never changed by the Agent objects you may go ahead const qualify the member.

The most conventional way to create a singleton has following requirements:
1) The constructor should be private and a static interface shall be provided which in turn creates a static object of the singleton class (which is a member of the class itself) and return it. Basically provide a global point of access.
2) You have to decide in advance if you want the users of the class to be able to extend it and design your class to support it if required.
If the above two requirements are met, there are a number of ways a singleton can be designed including the ones which would work with multi threaded applications.

A singleton has to have a private constructor, and then a static method to get an instance of the class, which is a private field in the class itself.

Since somebody already mentioned the wikipedia page, I'll also mention another implementation of the Singleton pattern done slightly differently.
If you look at the Ogre::Singleton class you'll see it done in a different way. It allows you to only call the constructor once (or an assertion happens). So in your setup, you call the constructor. Then at the end of the program, you get this instance and delete it.
It allows you to make a singleton instance, but allow it to be instantiated with different parameters. I don't like it nearly as much as the wikipedia implementation though since it requires you to manage the constructor/destructor of the singleton.

Define a static member of Agent that is of type Timing and initialize the member where it is defined. This is not strictly a Singleton any more but may model the behaviour you want better.

Related

A c++ class include a static member with the same type of itself. Why this pattern?

I inherited a project from a former colleague, and I found these code snippets (and some similar ones in SO questions: can a c++ class include itself as an member and static member object of a class in the same class)
// Service.h
class Service
{
// ...
public:
static Service sInstance;
void Somememberfunc();
//...
};
// Service.cpp
#include "Service.h"
Service Service::sInstance;
void Service::Somememberfunc()
{
//...
}
// Main.cpp
#include "Service.h"
void Fun()
{
Service &instance = Service::sInstance;
//...
instance.Somememberfunc();
//...
}
However, I did not find any explanation on when to use this pattern. And what are the advantages and disadvantages?
Notice that the member is a static, so it's part of the class, not of instantiated objects. This is important, because otherwise you would be trying to make a recursive member (since the member is part of the object, it also contains the same member and so on...), but this is not the case here.
The best pattern to describe this is: global variable. The static member is initialized before main() and can be accessed from any part of the program by including the header file. This is very convenient while implementing but becomes harder to handle the more complex the program gets and the longer you have to maintain it, so the general idea is to avoid this. Also, because there is no way to control the order of initialization, dependencies between different global variables can cause problems during startup.
Static member is roughly a global variable in the scope of the class.
Static members have also the advantage of visibility access (public/protected/private) to restreint its usage (file scope might be an alternative).
That member might be of type of the class.
Global are "easy" to (mis)use, as they don't require to think about architecture.
BUT (mutable) global are mostly discouraged as harder to reason about.
Acceptable usages IMO are for constants:
as for a matrix class, the null matrix, the diagonal one matrix.
for Temperature class, some specific value (absolute 0 (O Kelvin), temperature of water transformation(0 Celsius, 100 Celsius), ...)
in general NullObject, Default, ...
Singleton pattern. For example, you can use it to store your app configurations. And then you can easily access configurations anywhere(globally) within your app.
This is often used in the singleton design pattern
Visit https://en.wikipedia.org/wiki/Singleton_pattern

Determine if method or member can be protected or private

It is possible to check (for example by gcc) which methods or members can be moved to protected or private section?
Consider the following part of code:
class foo{
protected:
void foo_method_1(){};
int foo_member_var;
};
class bar : public foo{
void bar_method_1(){
foo_method_1();
}
};
If you want to determine which members and methods of the foo class can be private, you have to move all of them to the private section. So it will look like this:
class foo{
private:
void foo_method_1(){};
int foo_member_var;
};
...
Now it won't compile, here's the first error thrown by GCC:
prog.cpp:5:8: error: 'void foo::foo_method_1()' is private
void foo_method_1(){};
From that you know, that you have to move the foo_method_1 to the protected section. So it will look like this:
class foo{
private:
int foo_member_var;
protected:
void foo_method_1(){};
};
...
Now it will compile. You have to repeat this process for every single method and member in your class. For public section you can do it in the same way as described above.
You can't do this programmatically, no. And that's actually a good thing.
Sure, you could create a tool that integrated with a C++ parser, then — one-by-one — made certain members functions private and left any there that didn't cause an error in your program.
But, in order to do that, your entire program would need to be visible to that tool. Maybe if you have a simple project that's not a problem, but if you're writing a library that's literally impossible.
Even if you could do it, your resulting class design would be an absolute mess. Only a human programmer knows which parts of the API are designed for public consumption or not, and that's not always the same as which parts of the API are currently being consumed.
Stick to the manual approach, but don't just replicate the way the machine would do it, randomly guessing based on what compiles and what does not compile. Use your brain and your memory of what this class is supposed to do, to determine which functions should be public and which should not.
Ideally, try to get it right when you're first designing your class! You should be spending far more time designing your program than actually programming it, lest you very quickly end up with maintenance nightmares like this.
No. The compiler sees your code, not your design.

How to solve the problem of global access?

I'm building an app, and I need the wisdom of the SO community on a design issue.
In my application, there needs to be EXACTLY one instance of the class UiConnectionList, UiReader and UiNotifier.
Now, I have figured two ways to do this:
Method 1:
Each file has a global instance of that class in the header file itself.
Method 2: there is a separate globals.h file that contains single global instances of each class.
Example code:
Method 1
file: uiconnectionlist.h
#ifndef UICONNECTIONLIST_H
#define UICONNECTIONLIST_H
#include <QObject>
#include <QList>
class UiConnection;
class UiConnectionList : public QObject
{
Q_OBJECT
public:
UiConnectionList();
void addConnection(UiConnection* conn);
void removeConnection(UiConnection* conn);
private:
QList<UiConnection*> connList;
};
namespace Globals {
UiConnectionList connectionList;
}
#endif // UICONNECTIONLIST_H
file: uinotifier.h
#ifndef UINOTIFIER_H
#define UINOTIFIER_H
class UiNotifier
{
public:
UiNotifier();
};
namespace Globals {
UiNotifier uiNotifier;
}
#endif // UINOTIFIER_H
Method 2:
file: uiconnectionlist.h
#ifndef UICONNECTIONLIST_H
#define UICONNECTIONLIST_H
#include <QObject>
#include <QList>
class UiConnection;
class UiConnectionList : public QObject
{
Q_OBJECT
public:
UiConnectionList();
void addConnection(UiConnection* conn);
void removeConnection(UiConnection* conn);
private:
QList<UiConnection*> connList;
};
#endif // UICONNECTIONLIST_H
file: uinotifier.h
#ifndef UINOTIFIER_H
#define UINOTIFIER_H
class UiNotifier
{
public:
UiNotifier();
};
#endif // UINOTIFIER_H
file: globals.h
#ifndef GLOBALS_H
#define GLOBALS_H
#include "uiconnectionlist.h"
#include "uinotifier.h"
namespace Globals {
UiConnectionList connectionList;
UiNotifier uiNotifier;
}
#endif // GLOBALS_H
My Question
What is the better/right way to do this?
PS: I don't think that singleton is the right answer here, is it?
Thanks
Okay, so two answers have told me to make instances of UiConnectionList and UiNotifier, optionally wrap it in a UiContext and pass it around wherever required.
Could someone enumerate reasons (with examples) why passing around the context is better than having globally accessible variables.
This will help me judge what method is better (or better suited for my app).
Thanks
With your usage in globals.h you are going to have a multiple definition of Globals::UiConnectionList and Globals::UiNotifier for each compilation unit (.cc or .cpp file) that you use. This is not the way to make exactly one instance of those clases. You should use the singleton pattern as previous posters suggested.
If you didn't want to use the singleton pattern, the correct way is to define both clases in one compilation unit and then declare them as extern in the header file, the result is your intended one global instance of the class, but that won't prevent it from being copied or copy constructed. From your example you don't know the difference between declaration and definition.
I wouldn't do them global, instead create the three objects in your main and pass them to wherever they are needed. It is easier to follow for some other programmer because he sees when/where they are used. It gives you also better control when to create and destroy them than if you declare them global.
EDIT: to clarify normally programs get more and more complex as time goes by code being added by various developers with different ideas about design etc. In general (IMHO) once you start introducing globals in a program it encourages other programmers to do the same. That is why I prefer to have data passed to wherever it is used, in a procedural language as an argument or in an OOP language passed in via the ctor. It is then easier to see the dependencies.
First of all, you're right. This question has nothing to do with the Singleton pattern. It is a question of class design.
In this case i would prefer a different implementation than yours. In both of your examples you use a namespace called "Global". This is breaking the single concern principle, because here are a lot of objects having nothing else in common than being global accessible singletons. Instead of doing this you should encapsulate your singletons in the class declaration itself.
Look at this:
class UiConnectionList : public QObject
{
Q_OBJECT
public:
static UiConnectionList Connections; // This is your global varaible
public:
UiConnectionList();
void addConnection(UiConnection* conn);
void removeConnection(UiConnection* conn);
private:
QList<UiConnection*> connList;
};
Now your global connections can be accessed via UiConnectionList::Connections. The singleton implementation as a static variable isn't really good and should be done better. Especially to prevent the change of the pointer. But this is a different question.
The least you can do is to create a UiContext class/structure. Define all other things as member variables of this class. Then create a instance of UiContext in your main class and pass it to whichever class that requires it.
Even though, as people have mentioned already, your solution is faulty, I would avoid using a singleton. Using singleton to achieve your goal will make your code hard to test. Instead classes should depend on a pure virtual interface IConnetion or the like. Would sending instances to objects when they are created be implausible? You should at least have the option to do so (or preferably using a setter) to make your code testable. Note that the "extern" solution propsed by piotr more or less is the same as a singleton.
A lot of people disagree on whether to use the global/singleton pattern. I personally don't like it merely because it goes against the concept of loosely coupled class design.
Each class should do one thing, and should be able to exist by itself as much as possible. Having classes use a global UiConnectionList instance is not only creating maintainability issues, but its also means that the classes have to know where they're getting their instance from when they should preferably be told what list to use when they are created.
Think of a resource and its manager.
Resource *ResouceManager::createResource (string name)
{
Resource *res = new Resource(this);
res->SetName(name);
resourceList->Add(res);
return res;
}
In this example, the resource and its manager are very modestly coupled. The manager can find its created resources, and the resource knows which manager it was created in, but the resource is told which manager its owned by, not defining it itself (through a global manager).
The other way is to create a Resource (or a subclass) then ask a Manager to add it to its list essentially temporary coupling them, but until then they exist separately and aren't relying on pre-defined instances.
The better way to do this is to use the Singleton method. It has been tested and proven. Besides, the class would fail if I defined another UiConnectionList variable for example in my local scope.
void myfunction()
{
UiConnectionList connectionList;
// Any usage to connectionList would be cleared after this function exits.
}
Always remember when creating a singleton class. Lock (Private-tify?) the big four: Constructor, Copy Constructor, Assignment Operator, Destructor
Also, since you're using global variables, I'm assuming you don't need scoping or hiding. So the singleton method is the better way to do it.
Here's an example on implementing a singleton.
// Meyers singleton
static UiConnectionList* UiConnectionList::getSingletonPtr()
{
static UiConnectionList x;
return &x;
}

OO Programming Question: Global Object

I have probably a quite simple problem but I did not find a proper design decision yet.
Basically, I have 4 different classes and each of those classes has more than 10 methods.
Each of those classes should make use of the same TCP Socket; this object keeps a socket open to the server throughout program execution. My idea was to have the TCP obejct declared as "global" so that all other classes can use it:
classTCP TCPSocket;
class classA
{
private:
public:
classA();
...
};
class classB
{
private:
public:
classB();
...
};
Unfortunately, when declaring it like this my C++ compiler gives me an error message that some initialized data is written in the executable (???). So I am wondering if there is any other way I could declare this TCP object so that it is available for ALL the other classes and its methods?
Many thanks!
I'd suggest you keep the instance in your initialization code and pass it into each of the classes that needs it. That way, it's much easier to substitute a mock implementation for testing.
This sounds like a job for the Singleton design pattern.
The me sounds more for the right time to use Dependency Injection as i tend to avoid Singleton as much as i can (Singleton are just another way for accessing GLOBLAS, and its something to be avoided)
Singleton vs Dependency Injection has been already discussed on SO, check the "dependency injection" tag (sorry for not posting some links, but SO doens't allow me to post more than one link being a new user)
Wikipedia: Dependency Injection
As per your current code example, should be modified to allow injecting the Socket on the constructor of each Class:
class classA
{
private:
public:
classA(TCPSocket socket);
...
};
class classB
{
private:
public:
classB(TCPSocket socket);
...
};
Pass the socket into the constructor of each object. Then create a separate factory class which creates them and passes in the appropriate socket. All code uses the set of objects which are required to have the same socket should then create them via an instance of this factory object. This decouples the classes that should be using the single socket while still allowing the enforcement of the shared socket rule.
The best way to go about doing this is with a Singleton. Here is it's implementation in Java
Singleton Class:
public class SingletonTCPSocket {
private SingletonTCPSocket() {
// Private Constructor
}
private static class SingletonTCPSocketHolder {
private static final SingletonTCPSocket INSTANCE = new SingletonTCPSocket ();
}
public static SingletonTCPSocket getInstance() {
return SingletonTCPSocket.INSTANCE;
}
// Your Socket Specific Code Here
private TCPSocket mySocket;
public void OpenSocket();
}
The class that needs the socket:
public class ClassA {
public ClassA {
SingletonTCPSocket.getInstance().OpenSocket();
}
}
When you have an object which is unique in your program and used in a lot of places, you have several options:
pass a reference to the object everywhere
use a global more or less well hidden (singleton, mono-state, ...)
Each approach have its drawbacks. They are quite well commented and some have very strong opinions on those issues (do a search for "singleton anti-pattern"). I'll just give some of those, and not try to be complete.
passing a reference along is tedious and clutter the code; so you end up by keeping these references in some long lived object as well to reduce the number of parameters. When the time comes where the "unique" object is no more unique, you are ready? No: you have several paths to the unique object and you'll see that they now refer to different objects, and that they are used inconsistently. Debugging this can be a nightmare worse than modifying the code from a global approach to a passed along approach, and worse had not be planned in the schedules as the code was ready.
global like approach problem are even more well known. They introduce hidden dependencies (so reusing components is more difficult), unexpected side-effect (getting the right behaviour is more difficult, fixing a bug somewhere triggers a bug in another components), testing is more complicated, ...
In your case, having a socket is not something intrinsically unique. The possibility of having to use another one in your program or to reuse the components somewhere were that socket is no more unique seems quite high. I'd not go for a global approach but a parametrized one. Note that if your socket is intrinsically unique -- says it is for over the network logging -- you'd better encapsulate it in a object designed for that purpose. Logging for instance. And then it could make sense to use a global like feature.
As everyone has mentioned, globals are bad etc.
But to actually address the compile error that you have, I'm pretty sure it's because you're defining the global in a header file, which is being included in multiple files. What you want is this:
something.h
extern classTCP TCPSocket; //global is DECLARED here
class classA
{
private:
public:
classA();
...
};
something.cpp
classTCP TCPSocket; //global is DEFINED here

OO Programming Design question: Global Object part II

Sorry for reposting this, but for some reason I can not add comments to my older
post. Some people wanted to know the exact error message I get when trying to do
the following:
I have probably a quite simple problem but I did not find a proper
design decision yet. Basically, I have 4 different inherited classes and
each of those classes has more than 10 methods.
Each of those classes should make use of the same TCP Socket; this
object keeps a socket open to the server throughout program execution.
My idea was to have the TCP obejct declared as "global" so that all
other classes can use it:
classTCP TCPSocket;
class classA
{
private:
public:
classA();
virtual void method1();
...
};
class classB
{
private:
public:
classB();
virtual void method1();
...
};
and so on for classC and classD...
Unfortunately, when declaring it like this my Symbian GCC-E compiler gives me the
following error message
elf2e32 : Error: E1027: ELF File contains initialized writable data.
So I am wondering if there is any other way I could declare this
TCP object so that it is available for ALL the other classes and its
methods? classA() is the first method that will be called when
initialising this subsystem.
Many thanks!
There is very elegant way to retrieve static instances on demand.
classTCP& SingletonInstance()
{
static classTCP instance;
return instance;
}
Idea is using c++ feature to initialize local static variables only on demand.
You can support a class-wide static member by allowing both classA and classB to inherit from the same parent.
class BaseTCP {
static classTCP tcp;
// ...
};
class classA : BaseTCP {
// ...
};
class classB : BaseTCP {
// ...
};
Now classA and ClassB both share the same static member. The stipulation is that you now have to declare the static member outside of the BaseTCP class someplace, similar to:
classTCP BaseTCP::tcp;
Depending on your situation, this may be overkill...
Instead of using singletons, why don't you just create a classTCP instance and pass references to the other objects, each of which owns a reference (or pointer) to the single instance of classTCP.
This offers a much more flexible design - I think singletons generally suck and have much more limited use that generally believed. If you use a singleton, your classes classA, classB etc... have no option but to use the singleton instance. Using a more standard object composition design, you free the whole thing up.
Ask yourself questions like, what if I want the application to talk to >1 server? or what if I want to write some unit test code for classA? Writing unit test code for networking applications is a lot easier when you don't need to use real sockets but can use dummy ones that simply hold the chunks of data in ram. Add a comment if you want an example, because I'm off for lunch now:)
Doing it the way I suggest does not add significant complexity to the overall design but makes it much more open.
A Singleton pattern.