i reading item 4 of scott meyer's effective c++ trying show example static non-local object used across different translation units. highlighting problem whereby object used in 1 translation unit not know if has been initialised in other 1 prior usage. page 30 in third edition in case has copy.
the example such:
one file represents library:
class filesystem{ public: std::size_t numdisks() const; .... }; extern filesystem tfs;
and in client file:
class directory { public: directory(some_params); .... }; directory::directory(some_params) { ... std::size_t disks = tfs.numdisks(); ... }
my 2 questions thus:
1) if client code needs use tfs
, there sort of include statement. therefore surely code in 1 translation unit? not see how refer code in different translation unit? surely program 1 translation unit?
2) if client code included filesystem.h line extern filesystem tfs;
sufficient client code call tfs (i appreciate there run-time issue initialisation, talking compile-time scope)?
edit q1
the book says these 2 pieces of code in separate translation units. how client code use variable tfs
, knowing they're in separate translation units??
here's simplified example of how initialization across multiple tus can problematic.
gadget.h:
struct foo; extern foo gadget;
gadget.cpp:
#include <foo.h> #include <gadget.h> foo gadget(true, blue, 'x'); // initialized here
client.cpp:
#include <foo.h> #include <gadget.h> int do_something() { int x = gadget.frumple(); // problem! return bar(x * 2); }
the problem is not guaranteed gadget
object have been initialized time do_something()
refers it. guaranteed initializers within 1 tu completed before function in tu called.
(the solution replace extern foo gadget;
foo & gadget();
, implement in gadget.cpp { static foo impl; return impl; }
, use gadget().frumple()
.)
Comments
Post a Comment