I use global maps to register one or several objects of the same type. I started with using a global namespace for that purpose.
Take this for an example (code untested, just an example):
//frame.h
class frame
{
public:
frame(int id);
~frame();
};
namespace frame_globals
{
extern std::map<int, frame *> global_frameMap;
};
//frame.cpp
#include "frame.h"
namespace frame_globals
{
std::map<int, frame *> global_frameMap;
}
frame::frame(int id)
{
//[...]
//assuming this class is exclusively used with "new"!
frame_globals::global_frameMap[id] = this;
}
frame::~frame()
{
frame_globals::global_frameMap.erase(id);
}
This was a rather quick solution I used, but now I stumble again on the use case, where I need my objects registered and I asked myself if there was no better way, than using a global variable (I would like to get rid of that).
[EDIT: Seems to be incorrect]
A static member variable is (to my best knowledge) no option, because a static is inline in every object and I need it across all objects.
What is the best way to do this? Using a common parent comes to mind, but I want easy access to my frame class. How would you solve it?
Or do you know of a better way to register an object, so that I can get a pointer to it from somewhere else? So I might not exlusively need "new" and save "this"?