c++ - Sharing data between de-coupled functions\methods without globals -
basically need 2 or more functions reside in different source files , cannot know each other share data. globals instant solution, they're universally frowned upon. they're pretty inevitable in case?
here's simplified explanation of need using globals:
file1.c
int foo; void change_foo() { // calculation determine new value of foo foo = ... }
file2.c
extern int foo; void use_foo() { // value of foo // not aware of change_foo()'s existence can't call or called }
1) how 1 eliminate need global variable here? making int foo
static inside either function instantly couple both functions. defining variable inside main() , calling both functions within main() not option me.
2) there more elegant solution in oo language c++? 2 methods 2 different namespaces need share data.
3) can see problem happening often. 1 noticeable example need share resource or other entity (that cannot serializable in meaningful way) between 2 independent android activities. there no way around using globals (a class public static fields in example) or design pattern singleton?
one possibility (and not recommend it) map memory , both functions use mapped memory. extern statement works accessing data between files, when data cannot passed parameter in function call. caveat: global variables should avoided when possible because maintenance nightmare , need mutex (or similar) when being concurrently accessed different threads of execution.
in c++ variable can placed in singleton class, along getter , putter access methods. each file reference singleton class.
in c, data can 'file static' third file, file contains functions get/put variable. (that how it) each function wants access variable can call appropriate function in third file.
Comments
Post a Comment