C ++ global structure creates name conflict

I wrote a fairly extensive structure that controls the characters in physical modeling. Despite the fact that everyone warned me not to do this, I used the global public data structure to store information and called it State. It is not in the namespace. I make it globally accessible by declaring an external state state ;. The reason I did this is because this structure is needed everywhere in the application, and it’s very convenient for me to simply turn on my State.h and then write to state.var anywhere and read state.var anywhere. The frame also changes quickly, and I also feel that you do not need to worry about data transfer, synchronization, etc., when new components are introduced.

Anyway, now s *** got into the fan. I want to use one of the GUI classes of the GUI, and it already has its own member called state of type State. Their state is at least in the namespace, but that doesn't seem to matter, since inside the class I already use this namespace.

What can i do now?

+4
source share
3 answers

I probably do not understand the problem, but what is stopping you from doing

::state.var 

?

Plain :: means a global namespace, and when using global characters - well-known problems, and global variables also have their own set of problems (as a rule, C ++ code uses single lists instead), there is nothing magical evil to use global variable in the global namespace. ::errno is an example of such a variable, associated with almost any C and C ++ application on Unix-like platforms.

+5
source

Your only choice is to rip out your global and replace it with something normal. It hurts a lot, but you really have no other choice. This is why people recommend not using them in the first place.

In short, congratulations on learning a lesson at hand - don't use global variables.

+6
source

Well, there is a simple alternative:

 extern State state; State& mystate = state; namespace qt { class State; class Gui { public: void foo() { mystate.var = 3; } private: State* state; }; } 

... but there is also something called Technical Debt , and you borrow deeply.

+2
source

Source: https://habr.com/ru/post/1445215/


All Articles