Can I use a class constructor to run code in a cpp by itself?

I recently designed a struct like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// MyMap.h  
typedef std::map<std::string, std::function<void ()>> MyMap;  
extern MyMap g_mymap;

// MyMap.cpp  
My Map g_mymap;

// a.cpp
#include "MyMap.h"
class A {
    public: A() { g_mymap["a"] = [] () { std::cout << "function a"; }; }
}

static A a;

// b.cpp
#include "MyMap.h"
class B {
    public: B() { g_mymap["b"] = [] () { std::cout << "function b"; }; }
}

static B b;


It looks useful to implement strategy pattern because it makes a fully separate code block.
So I can add a function to the map simply by compiling a source file.
It's very simple. I don't need to edit another file.

But when I use it for my existing project, It makes some linking and runtime errors.(vs 2012)
I can't recognize exactly why because it is a huge project.

Anyway, I have a question that - Is this a safe use of class constructor?

I know that there is no fixed order of running, but in this case I think it doesn't matter. because they are independent.

But it is not a common pattern, so I can't decide to use it.
Dose someone have experience or opinion about it?
Last edited on
Ok, imagine what will happen if a.cpp will get initialized before MyMap.cpp:
A a; object will be created, which will try to access g_mymap object. Which does not exist, as MyMap.cpp where it belongs to did not run it initialization routines yet.

Congratulations: you stumbled upon common problem with global variables called static initialization order fiasco. You have code correctness of which depends on order of compilation units initialization. Which you cannot control.

Base rule is that you should not write code which depends on order of static initialization of variables across multiple compilation units.

http://www.parashift.com/c++-faq/static-init-order.html
Thanks. I didn't aware of that. Constructor of the map object can be a problem.

I think I can make a function that returns a reference of static variable or a pointer(of map instance). Then it will not make errors.

1
2
3
4
5
MyMap& get_mymap()
{
    static MyMap map;
    return map;
}


There is possibility that it has another problems...
Last edited on
I think I can make a function that returns a reference of static variable or a pointer(of map instance). Then it will not make errors.
Yes, it will be created on first access. If nothing with static storage duration tries to refer to it in its destructor, you are cool here.
Topic archived. No new replies allowed.