0

I've a class that has a member of type std::map. This map is created through calling a method of this class, makeMap(). It reads a config file and fills the map. In my scenario, I create one instance of this class and construct the map. Then recursively some problem is solved, involving many copies of the object. The map however stays the same (some other members are change).

Should such a map be static const? Since it does not change after creation and creation could be done when the first instance is created, it makes no sense to copy the map when the instance is being copied.

Is that a good use of static const?

AndyG
  • 39,700
  • 8
  • 109
  • 143
dani
  • 3,677
  • 4
  • 26
  • 60
  • Is it the same for all class instances? – πάντα ῥεῖ Oct 04 '16 at 12:53
  • Yes, it is created once and then copied. There is no other use of this. – dani Oct 04 '16 at 12:54
  • 2
    const - means it won't change; static - means there will be one version of it for all instances of the class. sounds like it's exactly what you want. – UKMonkey Oct 04 '16 at 12:55
  • @UKMonkey: If it's `const` it cannot change after creation, so `makeMap()` as OP described wouldn't work. If the map at some point should become ReadOnly, then mutations to it should be first checked against a flag. – AndyG Oct 04 '16 at 13:11
  • @AndyG: or it's made with the copy constructor - or it's a pointer. – UKMonkey Oct 04 '16 at 13:16
  • Actually, the answer there is exactly that: https://stackoverflow.com/questions/2636303/how-to-initialize-a-private-static-const-map-in-c – dani Oct 04 '16 at 13:23

1 Answers1

0

No. The reason is testability and coupling.

By making it static, you are preventing injecting a mock while testing. You are also making it harder for future changes to go in easily.

Especially since it's expensive to create, you dont want to do that while testing. You would want to inject a Mock or a Fake.

This is true even if it's const. Maybe one day it won't be?

You can read about the downsides of global state here:

https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil


Now for practicality, if you want that map to be created just once but have many instances of your object, you could create it in main() and use dependency injection and pass it in the constructor.

You could also use the Builder design pattern to solve this issue (while the builder could hold the map as a static object)

Community
  • 1
  • 1
user1708860
  • 1,683
  • 13
  • 32