Static pointer to a class method, if possible and meaningful - c++

Usually for singleton classes, one has to write all the time something like this:
SomeSingleton::GetInstance().someVariable
And I'm looking for a simplification that can be seen everywhere, so should be put in the (header and source) files of the class itself.
So, the (non-working) stuff should look something like this:
SomeSingleton.hpp:
class SomeSingleton {
//...
static SomeSingleton& GetInstance();
};
SomeSingleton& (*INSTANCE)();
SomeSingleton.cpp:
SomeSingleton& (* INSTANCE)() = SomeSingleton::GetInstance;
But this is misinterpreted as a redefinition, so doesn't work. If the declaration and the definition was in the same row, that would work, but then it would not work in a header used from everywhere. Assigning the pointer to the already declared INSTANCE variable wouldn't be simpler than simply defining the INSTANCE every file it is used in.
A workaround is to put a line
static SomeSingleton& (*INSTANCE)() = SomeSingleton::GetInstance;
into every file I use this and replace every SomeSingleton::GetInstance to INSTANCE which works but not ideal plus I'm not sure that from a design aspect it is clever to assign a singleton to a static variable (in a sense a static stuff to another static stuff).
Any ideas on this?

I think the only thing you are missing is extern in your header
extern SomeSingleton& (*INSTANCE)();

I usually try to make designs without singletons (and use dependency injection), which is better for unit testability.
But when really needed I use this pattern. You should also read up on Meyer's singleton pattern.
// header file
struct SomeSingleton
{
int value{ 42 };
};
SomeSingleton& GetGlobalInstance();
// cpp file
SomeSingleton& GetGlobalInstance()
{
static SomeSingleton data;
return data;
}
// some other cpp file
int main()
{
return GetGlobalInstance().value;
}

Related

Reusing objects in functions defined in C++ header

I have a function library in a header file, which includes the following function:
// Get a normally distributed float value in the range [0,1].
inline float GetNormDistrFloat()
{
std::random_device _RandomDevice;
std::normal_distribution<float> _NormalDistr(0.5, 2.0);
float val = -1;
do { val = _NormalDistr(_RandomDevice); } while(val < 0.0f || val > 1.0f);
return val;
}
This works well, however, I don't want to create the std::random_device and std::normal_distribution objects every time I call this function GetNormDistrFloat().
What is the "best" (correct) way in C++ to deal with this? I tried to just move those two object definitions outside the function, but that led to linker errors. Do I have to create a .cpp file for this header and initialize the objects there?
You could mark them as static variables which makes them behave almost like globals but only accessible inside the function:
void bar() {
static Foo foo_instance;
// Foo gets initialized only once
}
The main difference is the initialization. Globals get initialized at startup and static variables at their first access.
You can also make them globals, just make sure you do not define them in a header file, instead declare them as external:
// Header file
extern Foo foo_instance;
// Cpp file
Foo foo_instance;
Initialization of local static objects is thread-safe, however everything else is not.
I'm am not a fan of other solutions mentioned here; such as using globals or static locals. For one, state in functions is not a good idea as it's implicit and not obvious when reading code. It also makes things more complicated if you want to use the function from multiple threads. And it also makes testing more complicated. Instead, the "correct" way to handle state is to do the boring thing and create a class:
class NormDistrFloatGenerator
{
public:
NormDistFloatGenerator(const std::random_device& device,
const std::normal_distribution<float>& normal)
: m_device(device)
, m_normal(normal)
{}
float get_float() { // use member variables with same logic as in question }
private:
std::random_device m_device;
std::normal_distribution<float> m_normal;
};
At least if you write this class, you can test it properly, or use it in multiple threads. You only have to initialize this class once, and then you can repeatedly generate floats. If you really want to have something convenient, you can then do:
NormDistFloatGenerator& void makeGlobalFloatGenerator() {
static NormDistFloatGenerator(std::random_device, std::normal_distribution<float>(0.5, 2.0);
}
// at namespace scope
auto& g_float_generator = makeGlobalFloatGenerator();
You can then use g_float_generator everywhere. I'd really encourage you to avoid this approach. And even more so avoid the shortcuts others are suggesting.

Count number of objects created from a class [duplicate]

This question already has answers here:
Static variable for object count in c++ classes?
(3 answers)
Closed 3 months ago.
I would like to achieve a functionality where I can know how much object where created using a specific class.
I have tried the following:
myClass.h
class myClass {
private:
static int internalCounter;
int id;
public:
myClass(): id(internalCounter) {internalCounter++;}
}
The problem is that C++ doesn't allow this, and I'm not sure how to workaround this.
I have seen similar question in SA in which answer suggested something like:
myClass::internalCounter = 0;
But I don't think this right on the syntax level.
C++ does allow this. But the static variable needs a definition, and it sounds like that's missing. You'll need to put this in a source file (not the header)
int myClass::internalCounter = 0;
The = 0 is optional, since static variables are zero-initialised by default, but you might prefer to be explicit.
You need to define your static variable as
int myClass::internalCounter = 0;
in an implementation file.
The other suggestion you saw was almost right. You need something like this:
int myClass::internalCounter = 0;
But it needs to go in a source file (*.cpp) rather than a header. That line is necessary because the declaration on its own (in the header file) would never be instantiated otherwise. Resolving it in a source file means it will get picked up and instantiated within a specific translation unit.
You must define your static variable:
int myClass::internalCounter=0;
in your implementation file, its always best to read your compiler/linker output, in case of g++ it is:
main.cpp:(.text.startup+0x2): undefined reference to `myClass::internalCounter'
undefined reference means it was not defined, this is a hint on what you must fix in your code
I will suggest that, as you need to put your counter into a source file anyway, you take the definition of it out of the class and just put it into the anonymous namespace area. That takes some of the implementation detail of your class out of your header file.
If you are working in C++11 use atomic_int rather than int.
Use post-increment operator to make the action properly atomic.
myClass.h
class myClass
{
private:
int id;
public:
myClass();
// etc
};
myClass.cpp
#include <atomic>
#include "myClass.h"
namespace {
static std::atomic_int internalCounter;
}
myClass::myClass()
: id( internalCounter++ )
{
}
the operator++ post-increment on atomic_int is, at the name suggests, atomic, so it will be thread-safe.

Static member initialization using CRTP in separate library

After digging the web, I found some reference to a powerful pattern which exploits CRTP to allow instantiation at run-time of static members:
C++: Compiling unused classes
Initialization class for other classes - C++
And so on.
The proposed approach works well, unless such class hierarchy is placed into an external library.
Doing so, run-time initialization no more works, unless I manually #include somewhere the header file of derived classes. However, this defeats my main purpose - having the change to add new commands to my application without the need of changing other source files.
Some code, hoping it helps:
class CAction
{
protected:
// some non relevant stuff
public:
// some other public API
CAction(void) {}
virtual ~CAction(void) {}
virtual std::wstring Name() const = 0;
};
template <class TAction>
class CCRTPAction : public CAction
{
public:
static bool m_bForceRegistration;
CCRTPAction(void) { m_bForceRegistration; }
~CCRTPAction(void) { }
static bool init() {
CActionManager::Instance()->Add(std::shared_ptr<CAction>(new TAction));
return true;
}
};
template<class TAction> bool CCRTPAction<TAction>::m_bForceRegistration = CCRTPAction<TAction>::init();
Implementations being done this way:
class CDummyAction : public CCRTPAction<CDummyAction>
{
public:
CDummyAction() { }
~CDummyAction() { }
std::wstring Name() const { return L"Dummy"; }
};
Finally, here is the container class API:
class CActionManager
{
private:
CActionManager(void);
~CActionManager(void);
std::vector<std::shared_ptr<CAction>> m_vActions;
static CActionManager* instance;
public:
void Add(std::shared_ptr<CAction>& Action);
const std::vector<std::shared_ptr<CAction>>& AvailableActions() const;
static CActionManager* Instance() {
if (nullptr == instance) {
instance = new CActionManager();
}
return instance;
}
};
Everything works fine in a single project solution. However, if I place the above code in a separate .lib, the magic somehow breaks and the implementation classes (DummyAction and so on) are no longer instantiated.
I see that #include "DummyAction.h" somewhere, either in my library or in the main project makes things work, but
For our project, it is mandatory that adding Actions does not require changes in other files.
I don't really understand what's happening behind the scene, and this makes me uncomfortable. I really hate depending on solutions I don't fully master, since a bug could get out anywhere, anytime, possibly one day before shipping our software to the customer :)
Even stranger, putting the #include directive but not defining constructor/destructor in the header file still breaks the magic.
Thanks all for attention. I really hope someone is able to shed some light...
I can describe the cause of the problem; unfortunately I can't offer a solution.
The problem is that initialisation of a variable with static storage duration may be deferred until any time before the first use of something defined in the same translation unit. If your program never uses anything in the same translation unit as CCRTPAction<CDummyAction>::m_bForceRegistration, then that variable may never be initialised.
As you found, including the header in the translation unit that defines main will force it to be initialised at some point before the start of main; but of course that solution won't meet your first requirement. My usual solution to the problems of initialising static data across multiple translation units is to avoid static data altogether (and the Singleton anti-pattern doubly so, although that's the least of your problems here).
As explained in Mike's answer, the compiler determines that the static member CCRTPAction<CDummyAction>::m_bForceRegistration is never used, and therefore does not need to be initialised.
The problem you're trying to solve is to initialise a set of 'plugin' modules without having to #include their code in a central location. CTRP and templates will not help you here. I'm not aware of a (portable) way in C++ to generate code to initialise a set of plugin modules that are not referenced from main().
If you're willing to make the (reasonable) concession of having to list the plugin modules in a central location (without including their headers), there's a simple solution. I believe this is one of those extremely rare cases where a function-scope extern declaration is useful. You may consider this a dirty hack, but when there's no other way, a dirty hack becomes an elegant solution ;).
This code compiles to the main executable:
core/module.h
template<void (*init)()>
struct Module
{
Module()
{
init();
}
};
// generates: extern void initDummy(); Module<initDummy> DummyInstance
#define MODULE_INSTANCE(name) \
extern void init ## name(); \
Module<init ## name> name ## Instance
core/action.h
struct Action // an abstract action
{
};
void addAction(Action& action); // adds the abstract action to a list
main.cpp
#include "core/module.h"
int main()
{
MODULE_INSTANCE(Dummy);
}
This code implements the Dummy module and compiles to a separate library:
dummy/action.h
#include "core/action.h"
struct DummyAction : Action // a concrete action
{
};
dummy/init.cpp
#include "action.h"
void initDummy()
{
addAction(*new DummyAction());
}
If you wanted to go further (this part is not portable) you could write a separate program to generate a list of MODULE_INSTANCE calls, one for each module in your application, and output a generated header file:
generated/init.h
#include "core/module.h"
#define MODULE_INSTANCES \
MODULE_INSTANCE(Module1); \
MODULE_INSTANCE(Module2); \
MODULE_INSTANCE(Module3);
Add this as a pre-build step, and core/main.cpp becomes:
#include "generated/init.h"
int main()
{
MODULE_INSTANCES
}
If you later decide to load some or all of these modules dynamically, you can use exactly the same pattern to dynamically load, initialise and unload a dll. Please note that the following example is windows-specific, untested and does not handle errors:
core/dynamicmodule.h
struct DynamicModule
{
HMODULE dll;
DynamicModule(const char* filename, const char* init)
{
dll = LoadLibrary(filename);
FARPROC function = GetProcAddress(dll, init);
function();
}
~DynamicModule()
{
FreeLibrary(dll);
}
};
#define DYNAMICMODULE_INSTANCE(name) \
DynamicModule name ## Instance = DynamicModule(#name ".dll", "init" #name)
As Mike Seymour stated the static template stuff will not give you the dynamic loading facilities you want. You could load your modules dynamically as plug ins. Put dlls containing an action each into the working directory of the application and load these dlls dynamically at run-time. This way you will not have to change your source code in order to use different or new implementations of CAction.
Some frameworks make it easy to load custom plug ins, for example Qt.

C++ Best practices for constants

I have a whole bunch of constants that I want access to in different parts of my code, but that I want to have easy access to as a whole:
static const bool doX = true;
static const bool doY = false;
static const int maxNumX = 5;
etc.
So I created a file called "constants.h" and stuck them all in there and #included it in any file that needs to know a constant.
Problem is, this is terrible for compile times, since every time I change a constant, all files that constants.h reference have to be rebuilt. (Also, as I understand it, since they're static, I'm generating a copy of doX/doY/maxNumX in code every time I include constants.h in a new .cpp, leading to kilobytes of wasted space in the compiled EXE -- is there any way to see this?).
So, I want a solution. One that isn't "declare constants only in the files that use them", if possible.
Any suggestions?
The only alternative is to make your constants extern and define them in another .cpp file, but you'll lose potential for optimization, because the compiler won't know what value they have when compiling each .cpp`.
By the way, don't worry about the size increase: for integral types your constants are likely to be inlined directly in the generated machine code.
Finally, that static is not necessary, since by default const global variables are static in C++.
You declare them as extern in the header and define them in an implementation file.
That way, when you want to change their value, you modify the implementation file and no full re-compilation is necessary.
The problem in your variant isn't compilation-related, but logic related. They will not be globals since each translation unit will have its own copy of the variable.
EDIT:
The C++-ish way of doing it would actually wrapping them in a class:
//constants.h
class Constants
{
public:
static const bool doX;
static const bool doY;
static const int maxNumX;
}
//constants.cpp
const bool Constants::doX = true;
const bool Constants::doY = false;
const int Constants::maxNumX = 5;
I think your base assumption is off.
Your other headers are usually organized by keeping together what works together. For example, a class and its related methods or two classes heavily interlinked.
Why group all constants in a single header ? It does not make sense. It's about as bad an idea as a "global.h" header to include every single dependency easily.
In general, the constants are used in a particular context. For example, an enum used as a flag for a particular function:
class File {
public:
enum class Mode {
Read,
Write,
Append
};
File(std::string const& filename, Mode mode);
// ...
};
In this case, it is only natural that those constants live in the same header that the class they are bound to (and even within the class).
The other category of constants are those that just permeate the whole application. For example:
enum class Direction {
Up,
Down,
Right,
Left,
Forward,
Backward
};
... in a game where you want to express objects' move regarding the direction they are facing.
In this case, creating one header file for this specific set of constants is fine.
And if you really are worried about grouping those files together:
constants/
Direction.hpp
Sandwich.hpp
State.hpp
And you will neatly sidestep the issue of recompiling the whole application when you add a constant... though if you need to, do it, you're paying the cost only once, better than a wrong-sided design you'll have to live off with for the rest of your work.
What is the problem with this usage?
Do not declare a static type in header file, It does not do what you think it does.
When you declare a static in header file a copy of that variable gets created in each Translation Unit(TU) where you include that header file, SO each TU sees a different variable, this is opposite to your expectation of having a global.
Suggested Solution:
You should declare them as extern in a header file and define them in exactly one cpp file while include the header with extern in every cpp file where you want to access them.
Good Read:
How should i use extern?
Another approach which is best for compile times (but has some minor run-time cost) is to make the constants accessible via static methods in a class.
//constants.h
class Constants
{
public:
static bool doX();
static bool doY();
static int maxNumX();
};
//constants.cpp
bool Constants::doX() { return true; }
bool Constants::doY() { return false; }
int Constants::maxNumX() { return 42; }
The advantage of this approach is that you only recompile everything if you add/remove/change the declaration of a method in the header, while changing the value returned by any method requires only compiling constants.cpp (and linking, of course).
As with most things, this may or may not be the best is your particular case, but it is another option to consider.
The straight forward way is, to create non const symbols:
const bool doX = true;
const bool doY = false;
const int maxNumX = 5;
These values will be replaced by the compiler with the given values. Thats the most efficient way. This also of course leads to recompilation as soon as you modify or add values. But in most cases this should not raise practical problems.
Of course there are different solutions:
Using static consts, (or static const class members) the values can be modified without recompilation of all refered files - but thereby the values are held in a const data segment that will be called during runtime rather than being resolved at compile tine. If runtime perfomance is no issue (as it is for 90% of most typical code) thats OK.
The straight C++ way is using class enums rather than global const identifiers (as noted my Mathieu). This is more typesafe and besides this it works much as const: The symbols will be resolved at compile time.

Registering classes/functions/things before main()

Suppose I have a class called Poem.
class Poem{
virtual void recite() = 0;
}
And I have hundreds of .cpp and .hpp files which describe a subclass, like the following
class TheRaven : public Poem{
void recite() { std::cout << "NEVERMORE!" << endl; }
}
And the likes. And in the main function, I'd like to be able to just iterate through every single possible Poem subclasses and call their recite() function. So I made a class:
class PoemRegistry{
std::map<std::string, Poem*> poems;
PoemRegistry& getGlobal(); // returns a static global registry
void register(const std::string& poemname, Poem * thepoem);
};
And then for each poem subclass .cpp file, I put the following.
class TheRavenRegistor{
TheRavenRegistor(){
PoemRegistry::getGlobal().register("theraven", new TheRaven());
}
}
TheRavenRegistor registor();
ninja edit: I put the global class there, forgot about it
Making it easy, I make a shortcut with #define and templates.
Now, the question is, I just heard about the static class initialization fiasco. I suppose this will be immune against it, or is there something I am definitely missing here? Or is there something more elegant that can be used for this purpose?
This is an example for the Singleton design pattern. Don't use a static global, since the initialisation order is undefined across compilation units.
Instead use something like this:
PoemRegistry& PoemRegistry::getGlobal()
{
static PoemRegistry theRegistry; // construction guaranteed when first call
return theRegistry;
}
Make the getGlobal() method static:
class PoemRegistry
{
public:
static PoemRegistry& getGlobal();
...