How do I fix a sporadic crash when opening a PDF document using a PDFView object that was associated with another document?

Q: I am using PDFView and PDFDoc class in my application and it is
working great most of the time. Sometimes however I am getting a crash
when opening a new PDF document using pdfview.SetDoc().

I tried to use pdfview.CancelRendering() before setting the new doc,
as in the following code snippet, however it does not always work.

m_view.CancelRendering();
mp_doc.reset(new PDF::PDFDoc(ansifname));
if (mp_doc->InitSecurityHandler()) {
  m_view.SetDoc( *(mp_doc.get()) );
  ...
}

Could you please suggest what I am doing wrong in my code?
-----
A: The problem is that the document is be deleted (or closed) before
the viewer is reset to point to another document. A PDFView object may
try to access the document even if the rendering is cancelled.

m_view.CancelRendering();
mp_doc.reset(new PDF::PDFDoc(filename));
if (mp_doc->InitSecurityHandler()) {
  m_view.SetDoc( *(mp_doc.get()) );
  ...
}

To fix the problem simply delete/close PDFView before associated
PDFDoc. Another option is to call pdfview.SetDoc(pdfdoc) before
deleting the old document.

Since you are developing under C++, you may want to create PDFView on
the heap and delete the view before the document as follows:

// Close the old PDF view
mp_view.reset(0);

// Open a new PDF document
mp_doc.reset(new PDF::PDFDoc(filename));
if (mp_doc->InitSecurityHandler()) {
  mp_view.reset(new PDFView());
  mp_view->SetDoc( *(mp_doc.get()) );
  ...
}

The same rule applies to PDFNet development using C#, Java, or
VB.NET:
  A document should not not be closed if there are active views
referencing the document.