title: Interesting C++ dependency injection scheme
body: <p><strong>Background:</strong> I am a novice in C++. I have a C# project that I want to convert to C++ to gain some experience in writing some useful C++ code, beyond textbook examples. To this end, I have examined the code of some open source projects to get the feel of real C++, and also tried to do some refactoring in a fairly old project with some valgrind action and some adhoc statistics in debug build to confirm correctness (all with real input). (I have done a college project in C++ a number of years ago, but I don't count that as any real experience).</p>
  
  <p><strong>Actual question:</strong></p>
  
  <p>The C# project I am trying to convert to C++ uses lite weight dependency injection. Every class receives a "context" object in the constructor. It first inserts itself into the "context" before querying its own dependencies so that circular dependencies are not a problem.</p>
  
  <p>After some pondering I came up with a following scheme in C++. Every DI object receives its dependencies by reference in the constructor. I make all DI objects fields in one class (by value as sub-objects) and wire them up in the initialization list.</p>
  
  <pre class="lang-cpp prettyprint-override"><code>// Yes, the project is compiler for a toy programming language
  class Compiler {
      Logger log;
      Options options;
      ParserDriver parserDriver;
      DeclarationAnalysis declarationAnalysis;
      CodeTypeAnalysis codeTypeAnalysis;
      FlowAnalysis flowAnalysis;
      CodeGeneration codeGeneration;
      Check check;
      Typings typings;
      Operators operators;
      Symtab symtab;
  public:
      Compiler();
  };
  
  Compiler::Compiler() :
      log(),
      options(),
      parserDriver(log),
      declarationAnalysis(log, symtab, check),
      codeTypeAnalysis(log, symtab, operators, typings, check),
      flowAnalysis(log),
      codeGeneration(typings, symtab),
      check(log, symtab),
      typings(symtab),
      operators(symtab, log, typings),
      symtab()
  {}
  
  // Example DI object
  class DeclarationAnalysis {
      Logger* log;
      Symtab* symtab;
      Check* check;
  public:
      DeclarationAnalysis(Logger&amp;, Symtab&amp;, Check&amp;);
  }
  
  DeclarationAnalysis::DeclarationAnalysis(Logger&amp; log, Symtab&amp; symtab, Check&amp; chack) 
      : log(&amp;log), symtab(&amp;symtab), check(&amp;check) {}
  </code></pre>
  
  <p>Is code like this correct in a sense that it's safe, without undefined behavior (eg. <code>symtab</code> is initialized last but given as argument to other field's constructors)? It seems very elegant at first sight. Memory is packed, can even be allocated on the stack. Have I rediscovered an existing pattern?</p>