0

In C++ it's common to use static objects as part of other static object functions. The main challenge is order of static object initialization and destruction.

One of well known idioms for static objects lifetime/use management is Nifty counter, which suggests to keep a static counter and initialize the 'actual' instance/buffer as first translation unit will start to use the instance(counter == 0) and the destroy the buffer as the last translation unit instances are destroyed(counter == 0)

Question: what about static storage lifetime of nifty counter nifty_counter and stream_buf which is incapsulated in a single translation unit -> can be destroyed till all remaining translation unit instances are destroyed.

dbush
  • 205,898
  • 23
  • 218
  • 273
Martin Ayvazyan
  • 429
  • 1
  • 5
  • 16
  • 1
    `The main challenge is order of static object initialization and destruction`: There is a pattern that resolves this issue by putting the static storage object inside a function. It is created on first use and destroyed in reverse order of creation so you must simply make sure it is created before the last object that uses it. – Martin York Mar 15 '23 at 23:58
  • The point is static objects destruction in different translation units. How we can be sure the static instance in one translation unit will not be destroyed before another static instance of different translation unit is destroyed – Martin Ayvazyan Mar 16 '23 at 00:13
  • 1
    Care, attention to detail, and hard work. But it's better to be lazy and not put yourself into this position unless someone has a gun against your head. The whole "Globals are evil!" thing exists for a reason. – user4581301 Mar 16 '23 at 01:08
  • 1
    See: [Solving order of initialization:](https://stackoverflow.com/a/335746/14065) – Martin York Mar 16 '23 at 18:12

0 Answers0