c++ - Schwarz Counter for a vector -


i looking @ case have global static std::vector need guarantee initialized (constructed) before static objects in assortment of translation units.

when how handle come across 2 proposed solutions:

  1. have static object in global function used in place of global static object.
  2. schwarz counters

my concern using schwarz counter std::vector initialized twice. this link "a useful technique ensuring global object initialized once , before first use maintain count of number of translation units using it."

how work global initialized once? reasoning initialized twice. once in normal course of static initialization , once when first instance of schwarz counter initialized.

on related note, initialization code in schwarz counter constructor? can think of using placement new.

i can how i've implemented in past: design special "no-op" constructor, nothing, , use placement new in schwartz counter. like:

class foruseasstatic { public:     enum makectornoop { makectornoop };     foruseasstatic();   //  normal ctor, called schwartz counter.     foruseasstatic( makectornoop );                         //  no-op constructor, used when                         //  defining variable. }; 

formally, isn't guaranteed—the compiler allowed set memory 0 again before calling constructor, i've never heard of compiler does.

it possible put sort of flag in class itself, tested constructor. valid static objects, of course (since needs 0 initialization in order work).

another possible technique (which i've seen used in libraries) declare memory objects in assembler, or byte array if compiler has means of forcing alignment. data names not mangled, work, if formally undefined behavior. (for standard library, of course, library authors can request extensions in compiler them problem.)

finally: today, singleton idiom, or similar, preferred such work-arounds. mean have write myobj().xxx, rather myobj.xxx, not felt issue.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -