title: How to pass a reference of manager to the handler object?
body: <p>What I want to do is to write a small Manager/Handler class. A Manager distributes and manages Handles. Such a handle could be for example a simple filehandle.</p>
  
  <p>If a consumer wants to get a handle which already exists, the manager simply returns a shared_ptr. If the handle does not exist, the manager creates a new handle and then returns the shared_ptr.</p>
  
  <p>Inside the Manager, those shared_ptr's are stored in a simple STL-Map.
  If the last shared_ptr, which was assigned gets deleted, I want my manager to remove the related map-element, so that the handler object automatically gets destructed.</p>
  
  <p>This sounds a bit like garbage-collection(e.g. worker thread, which checks the usage count of the pointers), but I am sure it can be done more elegantly.</p>
  
  <p>How do I pass a reference of the manager instance to the handler object? (e.g. sth. like passing a unique_ptr(this) to the constructor of a new handler)</p>
  
  <pre><code>#include &lt;memory&gt;
  #include &lt;iostream&gt;
  #include &lt;map&gt;
  
  using namespace std;
  
  /*
   * Simple handler class, that actually does nothing.
   * This could be e.g. a Filehandler class or sth. like that
   */
  class Handler {
  private:
      int i;
  public:
      Handler(int i) :i(i) {}
      ~Handler() {}
      // Say who you are.
      void print(void) { cout &lt;&lt; "I am handler # " &lt;&lt; i &lt;&lt; endl; }
  };
  
  /*
   * This is the "manager" class, that manages all handles. A handle is identified
   * by an integer value. If a handle already exists, the Manager returns a shared_ptr,
   * if it does not exist, the manager creates a new handle.
   */
  class Manager {
  private:
      map&lt;int, shared_ptr&lt;Handler&gt; &gt; handles;
  public:
      Manager() {}
      ~Manager() {}
  
      shared_ptr&lt;Handler&gt; get_handler(int identifier) {
          shared_ptr&lt;Handler&gt; retval;
          auto it = handles.find(identifier);
  
          if(it != handles.end() ) {
              retval = it-&gt;second;
          } else {
              retval = shared_ptr&lt;Handler&gt;(new Handler(identifier));
              handles.insert( pair&lt;int, shared_ptr&lt;Handler&gt;&gt;(identifier, retval) );
          }
  
          return retval;
      }
  };
  
  int main(int argc, char** argv) {
      Manager m;
  
      // Handler 13 doesn't exist, so it gets allocated
      auto h = m.get_handler(13);
      // Manager knows about handler 13, so it returns the already existing shared_ptr
      auto i = m.get_handler(13);
  
      h.reset(); // Well... Let's assume we don't need h any more...
      // do some stuff...
      i-&gt;print();
      // ...
      i.reset(); // We also loose i. This is exactly the point where i want the manager to forget about the handle 13
  
      return 0;
  }
  </code></pre>