title: How can I "validate" CWnd* object?
body: <p>(There's a TL;DR on the last line)</p>
  
  <p>I'm implementing a handler to close selected windows open in a software application. Here's a rough code:</p>
  
  <pre><code>void CDlg_Dummy_Dialog::OnCloseWindows()
  {
      for (int i = 0; i &lt; m_WindowsInfo.size(); i++) {
          Window_Node *pWN = &amp;m_WindowsInfo.at(i);
          if (pWN-&gt;checked &amp;&amp; IsWindow(pWN-&gt;pWnd-&gt;GetSafeHwnd())) {
              pWN-&gt;pWnd-&gt;GetParentFrame()-&gt;SendMessage(WM_CLOSE);
          }
      }
  }
  </code></pre>
  
  <p>Here are some declarations of the parameters shown above:</p>
  
  <pre><code>struct Window_Node {
      CString name;
      CString path;
      CWnd *pWnd;
      BOOL checked;
      HICON icon;
      ....
  };
  
  class CDlg_Dummy_Dialog : public CDialog {
      ...
  protected:
      std::vector&lt;struct Window_Node&gt; m_WindowsInfo;
      ...
  }
  </code></pre>
  
  <p>Also, there can be multiple instances of <code>Window_Node</code> with different <code>pWnd</code> parameter, originating from a single <code>CDocument</code> class (ie. different types of windows exist to show different displays for the document).</p>
  
  <p><a href="https://i.stack.imgur.com/zp1sK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zp1sK.png" alt="enter image description here"></a></p>
  
  <p>For this software, if the first window of the document (which is always the "green" Window type in the diagram) is closed, all other windows associated with that document will automatically be closed with them. This is where the problem happens.</p>
  
  <p>If the user selects multiple windows from the same document (with the green window among them), it closes all windows by the time it finishes the first iteration, and all <code>pWnd</code> pointers are now pointing to a now unassigned memory. Therefore, when it tries to call <code>GetSafeHwnd()</code> on the next iteration, it prompts a memorry access violation error:</p>
  
  <pre><code>First-chance exception at 0x00000000521B4AD0 (mfc100d.dll) in Settle3D.exe: 0xC0000005: Access violation reading location 0x00000000136943E0.
  Unhandled exception at 0x00000000521B4AD0 (mfc100d.dll) in Settle3D.exe: 0xC000041D: An unhandled exception was encountered during a user callback.
  </code></pre>
  
  <p>I'm aware that the easy fix would be to iterate through the vector in the opposite direction. However, I am trying to integrate this method on several other software as well, and they don't necessarily organize their windows in the same manner.</p>
  
  <p>So, after all the long question above, here's TL;DR:</p>
  
  <p><strong>Is there any way to check if an instance of CWnd* is pointing to a valid window?</strong></p>