title: C++: Exposing pointers to class with managed memory
body: <p>I have the following setup:</p>
  
  <pre><code>class Foo {
  public:
      Foo() {}
  
      vector&lt;BigObject*&gt; mPointers;
  };
  class Bar {
  public:
      Foo *exposeSomeFoo() { return &amp;mFoos[42]; }
  private:
      vector&lt;Foo&gt; mFoos;
      vector&lt;BigObject&gt; mMemoryManaged;
  };
  </code></pre>
  
  <p>I'm basically trying to make sure that at no point in my code will someone accidentally use a <code>Foo</code> for which the <code>Bar</code> it was exposed from has gone out of scope.</p>
  
  <p>But this is obviously problematic. If I expose pointers to <code>Foo</code> like above, they become invalid once <code>Bar</code> goes out of scope. If I instead use <code>Foo exposeSomeFoo()</code>, the <code>mPointers</code> will become invalid once <code>Bar</code> goes out of scope, too - and returning copies seems like a bad idea if <code>mPointers</code> has a lot of elements!</p>
  
  <p>I've tried solving this by making a private copy constructor:</p>
  
  <pre><code>class Foo {
  public:
      Foo() {}
  
      vector&lt;BigObject*&gt; mPointers;
  private:
      Foo(const Foo&amp;);
  };
  </code></pre>
  
  <p>But then I get errors when I try to insert a <code>Foo</code> into <code>mFoos</code> from within <code>Bar</code>.</p>
  
  <p>There must be a paradigm that allows full memory safety while still allowing me to expose functionality like this. How can I expose, to code elsewhere, a composite object from <code>Bar</code> whose memory is managed specifically by <code>Bar</code> or at least in the compilation unit itself?</p>