title: Dynamic array of COM objects
body: <p>I have an ATL COM object which needs to expose a collection of other COM objects, so clients can find out how many objects are in the collection (via a simple <code>Count</code> property which I can provide) and access the objects using its index.  This collection of objects is dynamic - the count is not fixed - and I don't know how many there will be when my main (parent) object is constructed (so I can't create these objects in my <code>FinalConstruct</code> for example).  The objects I want to expose only have read-only properties.</p>
  
  <p>What I want to do is somehow create a <code>std::vector</code> of these objects the first time they are required.  I want to use ATL smart COM pointers where possible so I don't need to manually manage reference counts, etc. but I'm not sure whether I should be using <code>CComPtr</code>, 'CComQIPtr', etc.</p>
  
  <p>Assuming the objects I want to return are called <code>IChild</code>, I was hoping I could do something like this:</p>
  
  <pre><code>std::vector&lt;CComPtr&lt;IChild&gt; &gt; children;
  ...
  CComPtr&lt;IChild&gt; child;
  // Somehow instantiate an IChild?
  ...
  children.push_back(child);
  
  STDMETHODIMP Parent::GetAt(LONG index, IChild** pRet)
  {
    *pRet = children[index];
  }
  </code></pre>
  
  <p>If anyone has any pointers on how I can achieve this, I would be very welcome.  There is an <a href="http://vcfaq.mvps.org/com/12.htm" rel="nofollow noreferrer">excellent article on exposing a static object</a>, but I can't find anything on the particular problem in hand.</p>