get started on refcount for SfxShell

cf https://bugs.freedesktop.org/show_bug.cgi?id=70703#c36

Change-Id: Ie1821abc561ff2d79be55a9336dadf10dff64537
diff --git a/include/sfx2/sfxbasecontroller.hxx b/include/sfx2/sfxbasecontroller.hxx
index 6628200..2b726f1 100644
--- a/include/sfx2/sfxbasecontroller.hxx
+++ b/include/sfx2/sfxbasecontroller.hxx
@@ -97,7 +97,7 @@
         @onerror    -
     */
 
-    SfxBaseController( SfxViewShell* pView ) ;
+    SfxBaseController( rtl::Reference< SfxViewShell > pView ) ;
 
     /**___________________________________________________________________________________________________
         @short      -
@@ -352,7 +352,7 @@
 
     // FIXME: TL needs this in sw/source/ui/uno/unotxdoc.cxx now;
     // either the _Impl name should vanish or there should be an "official" API
-    SfxViewShell* GetViewShell_Impl() const;
+    rtl::Reference< SfxViewShell > GetViewShell_Impl() const;
     SAL_DLLPRIVATE sal_Bool HandleEvent_Impl( NotifyEvent& rEvent );
     SAL_DLLPRIVATE sal_Bool HasKeyListeners_Impl();
     SAL_DLLPRIVATE sal_Bool HasMouseClickListeners_Impl();
diff --git a/include/sfx2/shell.hxx b/include/sfx2/shell.hxx
index 93e2e78..8544803 100644
--- a/include/sfx2/shell.hxx
+++ b/include/sfx2/shell.hxx
@@ -20,6 +20,7 @@
 #define INCLUDED_SFX2_SHELL_HXX
 
 #include <com/sun/star/embed/VerbDescriptor.hpp>
+#include <rtl/ref.hxx>
 #include <rtl/ustring.hxx>
 #include <sal/config.h>
 #include <sal/types.h>
@@ -44,10 +45,8 @@
 class SfxSlotPool;
 class SvGlobalName;
 
-class SfxShellObject;
 class SfxShell;
 struct SfxShell_Impl;
-class SfxShellObject;
 class SfxDispatcher;
 class SfxViewFrame;
 class SfxSlot;
@@ -61,6 +60,8 @@
     class IUndoManager;
 }
 
+#define FREEZ(p) { delete (p); (p) = 0; }
+
 //====================================================================
 
 enum SfxInterfaceId
@@ -148,26 +149,36 @@
 {
     friend class SfxObjectItem;
 
+    oslInterlockedCount         m_refCount;
     SfxShell_Impl*              pImp;
     SfxItemPool*                pPool;
     ::svl::IUndoManager*        pUndoMgr;
 
 private:
                                 SfxShell( const SfxShell & ); // internal
-    SfxShell&                                   operator = ( const SfxShell & ); // internal
+    SfxShell&                   operator = ( const SfxShell & ); // internal
 
 protected:
                                 SfxShell();
-                                SfxShell( SfxViewShell *pViewSh );
+                                SfxShell( rtl::Reference< SfxViewShell > pViewSh );
 
-    SAL_DLLPRIVATE void SetViewShell_Impl( SfxViewShell* pView );
+    SAL_DLLPRIVATE void SetViewShell_Impl( rtl::Reference< SfxViewShell > pView );
     SAL_DLLPRIVATE void Invalidate_Impl( SfxBindings& rBindings, sal_uInt16 nId );
-    SAL_DLLPRIVATE SfxShellObject* GetShellObj_Impl() const;
-    SAL_DLLPRIVATE void SetShellObj_Impl( SfxShellObject* pObj );
 
 public:
                                 TYPEINFO();
     virtual                     ~SfxShell();
+    virtual void                dispose();
+
+    void acquire()
+    {
+        osl_atomic_increment( &m_refCount );
+    }
+    void release()
+    {
+        if (osl_atomic_decrement( &m_refCount ) == 0)
+            delete this;
+    }
 
     virtual SfxInterface*       GetInterface() const;
     static SfxInterface*        GetStaticInterface() { return 0; }
@@ -175,7 +186,7 @@
     void                        SetName( const OUString &rName );
     const OUString&             GetName() const;
 
-    SfxViewShell*               GetViewShell() const;
+    rtl::Reference< SfxViewShell > GetViewShell() const;
 
     void                        CallExec( SfxExecFunc pFunc, SfxRequest &rReq )
                                 { (*pFunc)(this, rReq); }
diff --git a/include/sfx2/viewfac.hxx b/include/sfx2/viewfac.hxx
index 687be03..d5fe248 100644
--- a/include/sfx2/viewfac.hxx
+++ b/include/sfx2/viewfac.hxx
@@ -37,7 +37,7 @@
     SfxViewFactory( SfxViewCtor fnC,
                     sal_uInt16 nOrdinal, const sal_Char* asciiViewName );
 
-    SfxViewShell *CreateInstance(SfxViewFrame *pViewFrame, SfxViewShell *pOldSh);
+    rtl::Reference< SfxViewShell >CreateInstance(SfxViewFrame *pViewFrame, rtl::Reference< SfxViewShell > pOldSh);
     sal_uInt16    GetOrdinal() const { return nOrd; }
 
     /// returns a legacy view name. This is "view" with an appended ordinal/ID.
diff --git a/include/sfx2/viewfrm.hxx b/include/sfx2/viewfrm.hxx
index 4c3b493..82450fc 100644
--- a/include/sfx2/viewfrm.hxx
+++ b/include/sfx2/viewfrm.hxx
@@ -128,7 +128,7 @@
                             { nAdjustPosPixelLock++; }
     void                    UnlockAdjustPosSizePixel()
                             { nAdjustPosPixelLock--; }
-    void                    DoAdjustPosSizePixel( SfxViewShell * pSh,
+    void                    DoAdjustPosSizePixel( rtl::Reference< SfxViewShell > pSh,
                                         const Point &rPos, const Size &rSize );
     void                    Show();
     sal_Bool                    IsVisible() const;
@@ -196,7 +196,7 @@
     SAL_DLLPRIVATE void SetDowning_Impl();
     SAL_DLLPRIVATE void GetDocNumber_Impl();
     SAL_DLLPRIVATE sal_Bool IsDowning_Impl() const;
-    SAL_DLLPRIVATE void SetViewShell_Impl( SfxViewShell *pVSh );
+    SAL_DLLPRIVATE void SetViewShell_Impl( rtl::Reference< SfxViewShell > pVSh );
     SAL_DLLPRIVATE void ReleaseObjectShell_Impl();
 
     SAL_DLLPRIVATE void GetState_Impl( SfxItemSet &rSet );
@@ -255,7 +255,7 @@
         @throws Exception
             if something goes wrong. The caller is responsible for handling this.
     */
-    SAL_DLLPRIVATE static SfxViewShell* LoadViewIntoFrame_Impl(
+    SAL_DLLPRIVATE static rtl::Reference< SfxViewShell > LoadViewIntoFrame_Impl(
                             const SfxObjectShell& i_rDoc,
                             const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& i_rFrame,
                             const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& i_rLoadArgs,
diff --git a/include/sfx2/viewsh.hxx b/include/sfx2/viewsh.hxx
index 315ae17..f6ce1f7 100644
--- a/include/sfx2/viewsh.hxx
+++ b/include/sfx2/viewsh.hxx
@@ -102,14 +102,14 @@
 private: \
     static SfxViewFactory *pFactory; \
 public: \
-    static SfxViewShell  *CreateInstance(SfxViewFrame *pFrame, SfxViewShell *pOldView); \
+    static rtl::Reference< SfxViewShell >CreateInstance(SfxViewFrame *pFrame, rtl::Reference< SfxViewShell >pOldView); \
     static void           RegisterFactory( sal_uInt16 nPrio = USHRT_MAX ); \
     static SfxViewFactory&Factory() { return *pFactory; } \
     static void           InitFactory()
 
 #define SFX_IMPL_NAMED_VIEWFACTORY(Class, AsciiViewName) \
     SfxViewFactory* Class::pFactory; \
-    SfxViewShell* Class::CreateInstance(SfxViewFrame *pFrame, SfxViewShell *pOldView) \
+    rtl::Reference< SfxViewShell > Class::CreateInstance(SfxViewFrame *pFrame, rtl::Reference< SfxViewShell >pOldView) \
     { return new Class(pFrame, pOldView); } \
     void Class::RegisterFactory( sal_uInt16 nPrio ) \
     { \
@@ -154,12 +154,12 @@
 
 public:
     // Iteration
-    static SfxViewShell*        GetFirst( const TypeId* pType = 0, sal_Bool bOnlyVisible = sal_True );
-    static SfxViewShell*        GetNext( const SfxViewShell& rPrev,
+    static rtl::Reference< SfxViewShell >        GetFirst( const TypeId* pType = 0, sal_Bool bOnlyVisible = sal_True );
+    static rtl::Reference< SfxViewShell >        GetNext( const SfxViewShell& rPrev,
                                          const TypeId* pType = 0, sal_Bool bOnlyVisible = sal_True );
-    static SfxViewShell*        Current();
+    static rtl::Reference< SfxViewShell >        Current();
 
-    static SfxViewShell*        Get( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController>& i_rController );
+    static rtl::Reference< SfxViewShell >        Get( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController>& i_rController );
 
     // Initialize Constructors/Destructors
                                 TYPEINFO();
diff --git a/sfx2/source/appl/app.cxx b/sfx2/source/appl/app.cxx
index fb84391..376cde7 100644
--- a/sfx2/source/appl/app.cxx
+++ b/sfx2/source/appl/app.cxx
@@ -361,7 +361,7 @@
                     pProgress->SetState( pProgress->GetState() );
             }
 
-            if ( pAppData_Impl->pViewFrame->GetViewShell() )
+            if ( pAppData_Impl->pViewFrame->GetViewShell().is() )
             {
                 SfxDispatcher* pDisp = pAppData_Impl->pViewFrame->GetDispatcher();
                 pDisp->Flush();
@@ -375,7 +375,7 @@
     // Otherwise, the CurrentComponent might not be correct, in case it has meanwhile
     // been reset to some other document, by some non-SFX component.
     // #i49133# / 2007-12-19 / frank.schoenheit@sun.com
-    if ( pFrame && pFrame->GetViewShell() )
+    if ( pFrame && pFrame->GetViewShell().is() )
         pFrame->GetViewShell()->SetCurrentDocument();
 }
 
diff --git a/sfx2/source/appl/appopen.cxx b/sfx2/source/appl/appopen.cxx
index 82c7b35..808fc76 100644
--- a/sfx2/source/appl/appopen.cxx
+++ b/sfx2/source/appl/appopen.cxx
@@ -1109,7 +1109,9 @@
     {
         // try to find the SfxFrame for the controller
         SfxFrame* pCntrFrame = NULL;
-        for ( SfxViewShell* pShell = SfxViewShell::GetFirst( 0, sal_False ); pShell; pShell = SfxViewShell::GetNext( *pShell, 0, sal_False ) )
+        for ( rtl::Reference< SfxViewShell > pShell = SfxViewShell::GetFirst( 0, sal_False );
+              pShell.is();
+              pShell = SfxViewShell::GetNext( *pShell, 0, sal_False ) )
         {
             if ( pShell->GetController() == xController )
             {
diff --git a/sfx2/source/appl/appserv.cxx b/sfx2/source/appl/appserv.cxx
index 4820ba9..c9656cb 100644
--- a/sfx2/source/appl/appserv.cxx
+++ b/sfx2/source/appl/appserv.cxx
@@ -1120,9 +1120,9 @@
             const SfxItemSet* pArgs = rReq.GetArgs();
             if ( pArgs && pView )
             {
-                SfxViewShell* pViewShell = pView->GetViewShell();
+                rtl::Reference< SfxViewShell > pViewShell (pView->GetViewShell());
                 SfxObjectShell* pObjShell = pView->GetObjectShell();
-                if ( pViewShell && pObjShell )
+                if ( pViewShell.is() && pObjShell )
                 {
                     SfxRequest aReq( SID_BASICIDE_SHOWWINDOW, SFX_CALLMODE_SYNCHRON, pObjShell->GetPool() );
                     aReq.SetArgs( *pArgs );
diff --git a/sfx2/source/appl/shutdownicon.cxx b/sfx2/source/appl/shutdownicon.cxx
index 1929c9b..6976d46 100644
--- a/sfx2/source/appl/shutdownicon.cxx
+++ b/sfx2/source/appl/shutdownicon.cxx
@@ -213,9 +213,9 @@
 
 class IdleTerminate : Timer
 {
-    Reference< XDesktop2 > m_xDesktop;
+    uno::Reference< XDesktop2 > m_xDesktop;
 public:
-    IdleTerminate (Reference< XDesktop2 > xDesktop)
+    IdleTerminate (uno::Reference< XDesktop2 > xDesktop)
     {
         m_xDesktop = xDesktop;
         Start();
@@ -257,7 +257,7 @@
 }
 
 
-ShutdownIcon::ShutdownIcon( const Reference< XComponentContext > & rxContext ) :
+ShutdownIcon::ShutdownIcon( const uno::Reference< XComponentContext > & rxContext ) :
     ShutdownIconServiceBase( m_aMutex ),
     m_bVeto ( false ),
     m_bListenForTermination ( false ),
@@ -285,16 +285,16 @@
 {
     if ( getInstance() && getInstance()->m_xDesktop.is() )
     {
-        Reference < XDispatchProvider > xDispatchProvider( getInstance()->m_xDesktop, UNO_QUERY );
+        uno::Reference < XDispatchProvider > xDispatchProvider( getInstance()->m_xDesktop, UNO_QUERY );
         if ( xDispatchProvider.is() )
         {
             com::sun::star::util::URL aDispatchURL;
             aDispatchURL.Complete = aURL;
 
-            Reference< util::XURLTransformer > xURLTransformer( util::URLTransformer::create( ::comphelper::getProcessComponentContext() ) );
+            uno::Reference< util::XURLTransformer > xURLTransformer( util::URLTransformer::create( ::comphelper::getProcessComponentContext() ) );
             try
             {
-                Reference< com::sun::star::frame::XDispatch > xDispatch;
+                uno::Reference< com::sun::star::frame::XDispatch > xDispatch;
 
                 xURLTransformer->parseStrict( aDispatchURL );
                 xDispatch = xDispatchProvider->queryDispatch( aDispatchURL, rTarget, 0 );
@@ -330,18 +330,18 @@
 {
     if ( getInstance() && getInstance()->m_xDesktop.is() )
     {
-        Reference < ::com::sun::star::frame::XFramesSupplier > xDesktop ( getInstance()->m_xDesktop, UNO_QUERY);
-        Reference < ::com::sun::star::frame::XFrame > xFrame( xDesktop->getActiveFrame() );
+        uno::Reference < ::com::sun::star::frame::XFramesSupplier > xDesktop ( getInstance()->m_xDesktop, UNO_QUERY);
+        uno::Reference < ::com::sun::star::frame::XFrame > xFrame( xDesktop->getActiveFrame() );
         if ( !xFrame.is() )
-            xFrame = Reference < ::com::sun::star::frame::XFrame >( xDesktop, UNO_QUERY );
+            xFrame = uno::Reference < ::com::sun::star::frame::XFrame >( xDesktop, UNO_QUERY );
 
         URL aTargetURL;
         aTargetURL.Complete = "slot:5500";
-        Reference< util::XURLTransformer > xTrans( util::URLTransformer::create( ::comphelper::getProcessComponentContext() ) );
+        uno::Reference< util::XURLTransformer > xTrans( util::URLTransformer::create( ::comphelper::getProcessComponentContext() ) );
         xTrans->parseStrict( aTargetURL );
 
-        Reference < ::com::sun::star::frame::XDispatchProvider > xProv( xFrame, UNO_QUERY );
-        Reference < ::com::sun::star::frame::XDispatch > xDisp;
+        uno::Reference < ::com::sun::star::frame::XDispatchProvider > xProv( xFrame, UNO_QUERY );
+        uno::Reference < ::com::sun::star::frame::XDispatch > xDisp;
         if ( xProv.is() )
         {
             if (aTargetURL.Protocol == "slot:")
@@ -355,7 +355,7 @@
             PropertyValue* pArg = aArgs.getArray();
             pArg[0].Name = "Referer";
             pArg[0].Value <<= OUString("private:user");
-            Reference< ::com::sun::star::frame::XNotifyingDispatch > xNotifyer( xDisp, UNO_QUERY );
+            uno::Reference< ::com::sun::star::frame::XNotifyingDispatch > xNotifyer( xDisp, UNO_QUERY );
             if ( xNotifyer.is() )
             {
                 EnterModalMode();
@@ -424,7 +424,7 @@
     // use constructor for filling up filters automatically!
     if ( ERRCODE_NONE == pThis->m_pFileDlg->GetError() )
     {
-        Reference< XFilePicker >    xPicker = pThis->m_pFileDlg->GetFilePicker();
+        uno::Reference< XFilePicker >    xPicker = pThis->m_pFileDlg->GetFilePicker();
 
         try
         {
@@ -432,8 +432,8 @@
             if ( xPicker.is() )
             {
 
-                Reference < XFilePickerControlAccess > xPickerControls ( xPicker, UNO_QUERY );
-                Reference < XFilterManager > xFilterManager ( xPicker, UNO_QUERY );
+                uno::Reference < XFilePickerControlAccess > xPickerControls ( xPicker, UNO_QUERY );
+                uno::Reference < XFilterManager > xFilterManager ( xPicker, UNO_QUERY );
 
                 Sequence< OUString >        sFiles = xPicker->getFiles();
                 int                         nFiles = sFiles.getLength();
@@ -441,7 +441,7 @@
                 int                         nArgs=3;
                 Sequence< PropertyValue >   aArgs(3);
 
-                Reference < com::sun::star::task::XInteractionHandler2 > xInteraction(
+                uno::Reference < com::sun::star::task::XInteractionHandler2 > xInteraction(
                     task::InteractionHandler::createWithParent(::comphelper::getProcessComponentContext(), 0) );
 
                 aArgs[0].Name = "InteractionHandler";
@@ -570,7 +570,7 @@
     if (pInst->m_bListenForTermination)
         return;
 
-    Reference< XDesktop2 > xDesktop = pInst->m_xDesktop;
+    uno::Reference< XDesktop2 > xDesktop = pInst->m_xDesktop;
     if ( ! xDesktop.is())
         return;
 
@@ -586,7 +586,7 @@
     if ( ! pInst)
         return;
 
-    Reference< XDesktop2 > xDesktop = pInst->m_xDesktop;
+    uno::Reference< XDesktop2 > xDesktop = pInst->m_xDesktop;
     if ( ! xDesktop.is())
         return;
 
@@ -595,7 +595,7 @@
     xDesktop->removeTerminateListener( pInst );
 
     // terminate desktop only if no tasks exist
-    Reference< XIndexAccess > xTasks ( xDesktop->getFrames(), UNO_QUERY );
+    uno::Reference< XIndexAccess > xTasks ( xDesktop->getFrames(), UNO_QUERY );
     if( xTasks.is() && xTasks->getCount() < 1 )
         new IdleTerminate( xDesktop );
 
@@ -639,7 +639,7 @@
     ::osl::ResettableMutexGuard aGuard( m_aMutex );
     m_pResMgr = pResMgr;
     aGuard.clear();
-    Reference < XDesktop2 > xDesktop = Desktop::create( m_xContext );
+    uno::Reference < XDesktop2 > xDesktop = Desktop::create( m_xContext );
     aGuard.reset();
     m_xDesktop = xDesktop;
 }
diff --git a/sfx2/source/appl/workwin.cxx b/sfx2/source/appl/workwin.cxx
index 9ca2087..7c4207c 100644
--- a/sfx2/source/appl/workwin.cxx
+++ b/sfx2/source/appl/workwin.cxx
@@ -770,7 +770,7 @@
 
     SfxInPlaceClient *pClient = 0;
     SfxViewFrame *pF = pFrame->GetCurrentViewFrame();
-    if ( pF && pF->GetViewShell() )
+    if ( pF && pF->GetViewShell().is() )
         pClient = pF->GetViewShell()->GetIPClient();
 
     if ( pClient )
diff --git a/sfx2/source/control/dispatch.cxx b/sfx2/source/control/dispatch.cxx
index 08e958e..c630c94 100644
--- a/sfx2/source/control/dispatch.cxx
+++ b/sfx2/source/control/dispatch.cxx
@@ -1948,8 +1948,8 @@
             // excecuted on a container dispatcher without a IPClient.
             if ( !bIsServerShell )
             {
-                SfxViewShell *pViewSh = pImp->pFrame->GetViewShell();
-                bIsServerShell = !pViewSh || !pViewSh->GetUIActiveClient();
+                rtl::Reference< SfxViewShell > pViewSh = pImp->pFrame->GetViewShell();
+                bIsServerShell = !pViewSh.is() || !pViewSh->GetUIActiveClient();
             }
 
             // Shell belongs to Container?
diff --git a/sfx2/source/control/shell.cxx b/sfx2/source/control/shell.cxx
index eaed943..282553f 100644
--- a/sfx2/source/control/shell.cxx
+++ b/sfx2/source/control/shell.cxx
@@ -72,7 +72,7 @@
 {
     OUString                 aObjectName;   // Name of Sbx-Objects
     SfxItemPtrMap            aItems;        // Data exchange on Item level
-    SfxViewShell*            pViewSh;       // SfxViewShell if Shell is
+    rtl::Reference< SfxViewShell > pViewSh; // SfxViewShell if Shell is
                                             // ViewFrame/ViewShell/SubShell list
     SfxViewFrame*            pFrame;        // Frame, if  <UI-active>
     SfxRepeatTarget*         pRepeatTarget; // SbxObjectRef xParent;
@@ -112,7 +112,8 @@
     the application of a SfxShell instance is very cheap.
 */
 
-:   pImp(0),
+:   m_refCount(0),
+    pImp(0),
     pPool(0),
     pUndoMgr(0)
 {
@@ -129,7 +130,7 @@
 
 //-------------------------------------------------------------------------
 
-SfxShell::SfxShell( SfxViewShell *pViewSh )
+SfxShell::SfxShell( rtl::Reference < SfxViewShell > pViewSh )
 
 /*  [Description]
 
@@ -138,7 +139,8 @@
     the application of a SfxShell instance is very cheap.
 */
 
-:   pImp(0),
+:   m_refCount(0),
+    pImp(0),
     pPool(0),
     pUndoMgr(0)
 {
@@ -154,7 +156,7 @@
 
 //--------------------------------------------------------------------
 
-SfxShell::~SfxShell()
+void SfxShell::dispose()
 
 /*  [Description]
 
@@ -166,8 +168,12 @@
 {
     DBG_DTOR(SfxShell, 0);
 
+    FREEZ(pImp);
+}
 
-    delete pImp;
+SfxShell::~SfxShell()
+{
+    dispose();
 }
 
 //--------------------------------------------------------------------
@@ -217,7 +223,7 @@
 
 //--------------------------------------------------------------------
 
-SfxViewShell* SfxShell::GetViewShell() const
+rtl::Reference< SfxViewShell > SfxShell::GetViewShell() const
 
 /*  [Description]
 
@@ -258,7 +264,7 @@
 {
     if ( pImp->pFrame )
         return pImp->pFrame;
-    if ( pImp->pViewSh )
+    if ( pImp->pViewSh.is() )
         return pImp->pViewSh->GetViewFrame();
     return 0;
 }
@@ -487,7 +493,7 @@
 */
 
 {
-    if ( !GetViewShell() )
+    if ( !GetViewShell().is() )
     {
         OSL_FAIL( "wrong Invalidate method called!" );
         return;
@@ -1034,8 +1040,8 @@
 void SfxShell::VerbExec(SfxRequest& rReq)
 {
     sal_uInt16 nId = rReq.GetSlot();
-    SfxViewShell *pViewShell = GetViewShell();
-    if ( pViewShell )
+    rtl::Reference< SfxViewShell > pViewShell = GetViewShell();
+    if ( pViewShell.is() )
     {
         sal_Bool bReadOnly = pViewShell->GetObjectShell()->IsReadOnly();
         com::sun::star::uno::Sequence < com::sun::star::embed::VerbDescriptor > aList = pViewShell->GetVerbs();
@@ -1099,7 +1105,7 @@
 
 SfxObjectShell* SfxShell::GetObjectShell()
 {
-    if ( GetViewShell() )
+    if ( GetViewShell().is() )
         return GetViewShell()->GetViewFrame()->GetObjectShell();
     else
         return NULL;
@@ -1159,7 +1165,7 @@
     pImp->maContextChangeBroadcaster.Initialize(rsContextName);
 }
 
-void SfxShell::SetViewShell_Impl( SfxViewShell* pView )
+void SfxShell::SetViewShell_Impl( rtl::Reference< SfxViewShell > pView )
 {
     pImp->pViewSh = pView;
 }
diff --git a/sfx2/source/dialog/basedlgs.cxx b/sfx2/source/dialog/basedlgs.cxx
index f51af2b..ebdce32 100644
--- a/sfx2/source/dialog/basedlgs.cxx
+++ b/sfx2/source/dialog/basedlgs.cxx
@@ -376,7 +376,7 @@
     else if( rEvt.GetType() == EVENT_KEYINPUT )
     {
         // First, allow KeyInput for Dialog functions ( TAB etc. )
-        if ( !ModelessDialog::Notify( rEvt ) && SfxViewShell::Current() )
+        if ( !ModelessDialog::Notify( rEvt ) && SfxViewShell::Current().is() )
             // then also for valid global accelerators.
             return SfxViewShell::Current()->GlobalKeyInput_Impl( *rEvt.GetKeyEvent() );
         return sal_True;
@@ -467,7 +467,7 @@
     else if( rEvt.GetType() == EVENT_KEYINPUT )
     {
         // First, allow KeyInput for Dialog functions
-        if ( !FloatingWindow::Notify( rEvt ) && SfxViewShell::Current() )
+        if ( !FloatingWindow::Notify( rEvt ) && SfxViewShell::Current().is() )
             // then also for valid global accelerators.
             return SfxViewShell::Current()->GlobalKeyInput_Impl( *rEvt.GetKeyEvent() );
         return sal_True;
diff --git a/sfx2/source/dialog/dockwin.cxx b/sfx2/source/dialog/dockwin.cxx
index 0b453de..d9bef45 100644
--- a/sfx2/source/dialog/dockwin.cxx
+++ b/sfx2/source/dialog/dockwin.cxx
@@ -1791,7 +1791,7 @@
     else if( rEvt.GetType() == EVENT_KEYINPUT )
     {
         // First, allow KeyInput for Dialog functions
-        if ( !DockingWindow::Notify( rEvt ) && SfxViewShell::Current() )
+        if ( !DockingWindow::Notify( rEvt ) && SfxViewShell::Current().is() )
             // then also for valid global accelerators.
             return SfxViewShell::Current()->GlobalKeyInput_Impl( *rEvt.GetKeyEvent() );
         return sal_True;
diff --git a/sfx2/source/dialog/securitypage.cxx b/sfx2/source/dialog/securitypage.cxx
index fba3f5c..6b2c058 100644
--- a/sfx2/source/dialog/securitypage.cxx
+++ b/sfx2/source/dialog/securitypage.cxx
@@ -54,8 +54,8 @@
     bool QueryState( sal_uInt16 _nSlot, bool& _rValue )
     {
         bool bRet = false;
-        SfxViewShell* pViewSh = SfxViewShell::Current();
-        if (pViewSh)
+        rtl::Reference< SfxViewShell > pViewSh = SfxViewShell::Current();
+        if (pViewSh.is())
         {
             const SfxPoolItem* pItem;
             SfxDispatcher* pDisp = pViewSh->GetDispatcher();
@@ -256,8 +256,8 @@
     {
         bool bIsHTMLDoc = false;
         bool bProtect = true, bUnProtect = false;
-        SfxViewShell* pViewSh = SfxViewShell::Current();
-        if (pViewSh)
+        rtl::Reference< SfxViewShell > pViewSh = SfxViewShell::Current();
+        if (pViewSh.is())
         {
             const SfxPoolItem* pItem;
             SfxDispatcher* pDisp = pViewSh->GetDispatcher();
diff --git a/sfx2/source/dialog/templdlg.cxx b/sfx2/source/dialog/templdlg.cxx
index ad869f5..6512533 100644
--- a/sfx2/source/dialog/templdlg.cxx
+++ b/sfx2/source/dialog/templdlg.cxx
@@ -2279,8 +2279,8 @@
     if(ISA(SfxTemplateDialog_Impl))
     {
         SfxViewFrame *pViewFrame = pBindings->GetDispatcher_Impl()->GetFrame();
-        SfxViewShell *pVu = pViewFrame->GetViewShell();
-        Window *pAppWin = pVu ? pVu->GetWindow(): 0;
+        rtl::Reference< SfxViewShell > pVu = pViewFrame->GetViewShell();
+        Window *pAppWin = pVu.is() ? pVu->GetWindow(): 0;
         if(pAppWin)
             pAppWin->GrabFocus();
     }
diff --git a/sfx2/source/doc/objcont.cxx b/sfx2/source/doc/objcont.cxx
index cbaccb4..ca9ad63 100644
--- a/sfx2/source/doc/objcont.cxx
+++ b/sfx2/source/doc/objcont.cxx
@@ -118,7 +118,7 @@
     // DoDraw can only be called when no printing is done, otherwise
     // the printer may be turned off
     SfxViewFrame *pFrame = SfxViewFrame::GetFirst( this );
-    if ( pFrame && pFrame->GetViewShell() &&
+    if ( pFrame && pFrame->GetViewShell().is() &&
          pFrame->GetViewShell()->GetPrinter() &&
          pFrame->GetViewShell()->GetPrinter()->IsPrinting() )
          return ::boost::shared_ptr<GDIMetaFile>();
diff --git a/sfx2/source/doc/objmisc.cxx b/sfx2/source/doc/objmisc.cxx
index 81b8d5d..7e267b3 100644
--- a/sfx2/source/doc/objmisc.cxx
+++ b/sfx2/source/doc/objmisc.cxx
@@ -1395,7 +1395,7 @@
     MarkData_Impl *pMark = Get_Impl()->pMarkData;
     if( pMark )
     {
-        SfxViewShell* pSh = pMark->pFrame->GetViewShell();
+        rtl::Reference< SfxViewShell > pSh = pMark->pFrame->GetViewShell();
         if( !pMark->aUserData.isEmpty() )
             pSh->ReadUserData( pMark->aUserData, sal_True );
         else if( !pMark->aMark.isEmpty() )
diff --git a/sfx2/source/doc/objxtor.cxx b/sfx2/source/doc/objxtor.cxx
index 154ed3f..08cf2c9 100644
--- a/sfx2/source/doc/objxtor.cxx
+++ b/sfx2/source/doc/objxtor.cxx
@@ -588,8 +588,8 @@
     for ( SfxViewFrame* pFrm = SfxViewFrame::GetFirst( this );
           pFrm; pFrm = SfxViewFrame::GetNext( *pFrm, this ) )
     {
-        DBG_ASSERT(pFrm->GetViewShell(),"No Shell");
-        if ( pFrm->GetViewShell() )
+        DBG_ASSERT(pFrm->GetViewShell().is(),"No Shell");
+        if ( pFrm->GetViewShell().is() )
         {
             sal_uInt16 nRet = pFrm->GetViewShell()->PrepareClose( bUI, bForBrowsing );
             if ( nRet != sal_True )
diff --git a/sfx2/source/doc/printhelper.cxx b/sfx2/source/doc/printhelper.cxx
index 7be793d..e528f52 100644
--- a/sfx2/source/doc/printhelper.cxx
+++ b/sfx2/source/doc/printhelper.cxx
@@ -311,7 +311,7 @@
 //  XPrintable
 //________________________________________________________________________________________________________
 
-void SfxPrintHelper::impl_setPrinter(const uno::Sequence< beans::PropertyValue >& rPrinter,SfxPrinter*& pPrinter,sal_uInt16& nChangeFlags,SfxViewShell*& pViewSh)
+void SfxPrintHelper::impl_setPrinter(const uno::Sequence< beans::PropertyValue >& rPrinter, SfxPrinter*& pPrinter, sal_uInt16& nChangeFlags, rtl::Reference< SfxViewShell > &pViewSh)
 
 {
     // Get old Printer
@@ -452,12 +452,12 @@
     // object already disposed?
     SolarMutexGuard aGuard;
 
-    SfxViewShell* pViewSh = NULL;
+    rtl::Reference< SfxViewShell > pViewSh(NULL);
     SfxPrinter* pPrinter = NULL;
     sal_uInt16 nChangeFlags = 0;
     impl_setPrinter(rPrinter,pPrinter,nChangeFlags,pViewSh);
     // set new printer
-    if ( pViewSh && pPrinter )
+    if ( pViewSh.is() && pPrinter )
         pViewSh->SetPrinter( pPrinter, nChangeFlags, false );
 }
 
@@ -594,8 +594,8 @@
                                 SfxViewFrame::GetFirst( m_pData->m_pObjectShell, sal_False ) : 0;
     if ( !pViewFrm )
         return;
-    SfxViewShell* pView = pViewFrm->GetViewShell();
-    if ( !pView )
+    rtl::Reference< SfxViewShell > pView (pViewFrm->GetViewShell());
+    if ( !pView.is() )
         return;
     sal_Bool bMonitor = sal_False;
     // We need this information at the end of this method, if we start the vcl printer
diff --git a/sfx2/source/doc/printhelper.hxx b/sfx2/source/doc/printhelper.hxx
index 1ef8bd8..5ef4d73 100644
--- a/sfx2/source/doc/printhelper.hxx
+++ b/sfx2/source/doc/printhelper.hxx
@@ -31,6 +31,7 @@
 #include <com/sun/star/uno/Any.hxx>
 #include <com/sun/star/lang/XInitialization.hpp>
 #include <osl/mutex.hxx>
+#include <rtl/ref.hxx>
 #include <cppuhelper/implbase3.hxx>
 
 struct  IMPL_PrintListener_DataContainer;
@@ -60,7 +61,7 @@
 
     osl::Mutex m_aMutex;
     IMPL_PrintListener_DataContainer* m_pData ;
-    virtual void impl_setPrinter(const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& rPrinter,SfxPrinter*& pPrinter,sal_uInt16& nChangeFlags,SfxViewShell*& pViewSh);
+    virtual void impl_setPrinter(const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& rPrinter,SfxPrinter*& pPrinter,sal_uInt16& nChangeFlags,rtl::Reference< SfxViewShell >& pViewSh);
 } ;
 
 #endif
diff --git a/sfx2/source/doc/sfxbasemodel.cxx b/sfx2/source/doc/sfxbasemodel.cxx
index 996fdb0..d76e400 100644
--- a/sfx2/source/doc/sfxbasemodel.cxx
+++ b/sfx2/source/doc/sfxbasemodel.cxx
@@ -1051,7 +1051,7 @@
         SfxViewFrame* pFrame = SfxViewFrame::GetFirst( m_pData->m_pObjectShell );
         if ( pFrame )
         {
-            SvBorder aBorder = pFrame->GetBorderPixelImpl( pFrame->GetViewShell() );
+            SvBorder aBorder = pFrame->GetBorderPixelImpl( pFrame->GetViewShell().get() );
 
             Sequence< sal_Int32 > aBorderSeq(4);
             aBorderSeq[0] = aBorder.Left();
@@ -3247,7 +3247,7 @@
         if ( !pActFrame || pActFrame->GetObjectShell() != m_pData->m_pObjectShell )
             pActFrame = SfxViewFrame::GetFirst( m_pData->m_pObjectShell );
 
-        if ( !pActFrame || !pActFrame->GetViewShell() )
+        if ( !pActFrame || !pActFrame->GetViewShell().is() )
             // currently no frame for this document at all or View is under construction
             return Reference < container::XIndexAccess >();
 
@@ -4311,8 +4311,8 @@
     {
         xPreviousController.clear();
     }
-    SfxViewShell* pOldViewShell = SfxViewShell::Get( xPreviousController );
-    OSL_ENSURE( !xPreviousController.is() || ( pOldViewShell != NULL ),
+    rtl::Reference< SfxViewShell > pOldViewShell = SfxViewShell::Get( xPreviousController );
+    OSL_ENSURE( !xPreviousController.is() || ( pOldViewShell.is() ),
         "SfxBaseModel::createViewController: invalid old controller!" );
 
     // a guard which will clean up in case of failure
@@ -4324,9 +4324,9 @@
 
     // delegate to SFX' view factory
     pViewFrame->GetBindings().ENTERREGISTRATIONS();
-    SfxViewShell* pViewShell = pViewFactory->CreateInstance( pViewFrame, pOldViewShell );
+    rtl::Reference< SfxViewShell > pViewShell = pViewFactory->CreateInstance( pViewFrame, pOldViewShell );
     pViewFrame->GetBindings().LEAVEREGISTRATIONS();
-    ENSURE_OR_THROW( pViewShell, "invalid view shell provided by factory" );
+    ENSURE_OR_THROW( pViewShell.is(), "invalid view shell provided by factory" );
 
     // by setting the ViewShell it is prevented that disposing the Controller will destroy this ViewFrame also
     pViewFrame->GetDispatcher()->SetDisableFlags( 0 );
diff --git a/sfx2/source/menu/mnumgr.cxx b/sfx2/source/menu/mnumgr.cxx
index 5906ab5..a79eb75 100644
--- a/sfx2/source/menu/mnumgr.cxx
+++ b/sfx2/source/menu/mnumgr.cxx
@@ -102,8 +102,8 @@
 //-------------------------------------------------------------------------
 void InsertVerbs_Impl( SfxBindings* pBindings, const com::sun::star::uno::Sequence < com::sun::star::embed::VerbDescriptor >& aVerbs, Menu* pMenu )
 {
-    SfxViewShell *pView = pBindings->GetDispatcher()->GetFrame()->GetViewShell();
-    if ( pView && aVerbs.getLength() )
+    rtl::Reference< SfxViewShell > pView = pBindings->GetDispatcher()->GetFrame()->GetViewShell();
+    if ( pView.is() && aVerbs.getLength() )
     {
         SfxObjectShell* pDoc = pView->GetObjectShell();
         pMenu->InsertSeparator();
diff --git a/sfx2/source/view/frame.cxx b/sfx2/source/view/frame.cxx
index e1999d5..04cf3c3 100644
--- a/sfx2/source/view/frame.cxx
+++ b/sfx2/source/view/frame.cxx
@@ -358,7 +358,7 @@
     // updateDescriptor) to save time.
 
     SfxViewFrame* pViewFrame = GetCurrentViewFrame();
-    if( pViewFrame && pViewFrame->GetViewShell() )
+    if( pViewFrame && pViewFrame->GetViewShell().is() )
     {
         const SfxMedium *pMed = GetCurrentDocument()->GetMedium();
         sal_Bool bReadOnly = pMed->GetOpenMode() == SFX_STREAM_READONLY;
@@ -475,7 +475,7 @@
     }
 
     SfxViewFrame* pView = GetCurrentViewFrame();
-    if( pView && pView->GetViewShell() && pChildArr )
+    if( pView && pView->GetViewShell().is() && pChildArr )
     {
         sal_uInt16 nCount = pChildArr->size();
         for ( sal_uInt16 n=0; n<nCount; n++)
@@ -699,7 +699,7 @@
 
 ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController > SfxFrame::GetController() const
 {
-    if ( pImp->pCurrentViewFrame && pImp->pCurrentViewFrame->GetViewShell() )
+    if ( pImp->pCurrentViewFrame && pImp->pCurrentViewFrame->GetViewShell().is() )
         return pImp->pCurrentViewFrame->GetViewShell()->GetController();
     else
         return ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController > ();
@@ -849,7 +849,8 @@
     }
 
     Window* pFocusWindow = &GetWindow();
-    if ( GetCurrentViewFrame() && GetCurrentViewFrame()->GetViewShell() && GetCurrentViewFrame()->GetViewShell()->GetWindow() )
+    if ( GetCurrentViewFrame() && GetCurrentViewFrame()->GetViewShell().is() &&
+         GetCurrentViewFrame()->GetViewShell()->GetWindow() )
         pFocusWindow = GetCurrentViewFrame()->GetViewShell()->GetWindow();
 
     if( !pFocusWindow->HasChildPathFocus() )
@@ -886,7 +887,7 @@
         {
             // check for IPClient that contains UIactive object or object that is currently UI activating
             SfxWorkWindow *pWork = GetWorkWindow_Impl();
-            SfxInPlaceClient* pClient = GetCurrentViewFrame()->GetViewShell() ? GetCurrentViewFrame()->GetViewShell()->GetUIActiveIPClient_Impl() : 0;
+            SfxInPlaceClient* pClient = GetCurrentViewFrame()->GetViewShell().is() ? GetCurrentViewFrame()->GetViewShell()->GetUIActiveIPClient_Impl() : 0;
             if ( pClient )
             {
                 uno::Reference < lang::XUnoTunnel > xObj( pClient->GetObject()->getComponent(), uno::UNO_QUERY );
diff --git a/sfx2/source/view/frame2.cxx b/sfx2/source/view/frame2.cxx
index c9c4d35..43b3801 100644
--- a/sfx2/source/view/frame2.cxx
+++ b/sfx2/source/view/frame2.cxx
@@ -108,7 +108,7 @@
 
     if ( rNEvt.GetType() == EVENT_GETFOCUS )
     {
-        if ( pView->GetViewShell() && !pView->GetViewShell()->GetUIActiveIPClient_Impl() && !pFrame->IsInPlace() )
+        if ( pView->GetViewShell().is() && !pView->GetViewShell()->GetUIActiveIPClient_Impl() && !pFrame->IsInPlace() )
         {
             OSL_TRACE("SfxFrame: GotFocus");
             pView->MakeActive_Impl( sal_False );
@@ -144,16 +144,16 @@
     if ( nType == EVENT_KEYINPUT || nType == EVENT_KEYUP )
     {
         SfxViewFrame* pView = pFrame->GetCurrentViewFrame();
-        SfxViewShell* pShell = pView ? pView->GetViewShell() : NULL;
-        if ( pShell && pShell->HasKeyListeners_Impl() && pShell->HandleNotifyEvent_Impl( rNEvt ) )
+        rtl::Reference< SfxViewShell > pShell = pView ? pView->GetViewShell() : NULL;
+        if ( pShell.is() && pShell->HasKeyListeners_Impl() && pShell->HandleNotifyEvent_Impl( rNEvt ) )
             return sal_True;
     }
     else if ( nType == EVENT_MOUSEBUTTONUP || nType == EVENT_MOUSEBUTTONDOWN )
     {
         Window* pWindow = rNEvt.GetWindow();
         SfxViewFrame* pView = pFrame->GetCurrentViewFrame();
-        SfxViewShell* pShell = pView ? pView->GetViewShell() : NULL;
-        if ( pShell )
+        rtl::Reference< SfxViewShell > pShell = pView ? pView->GetViewShell() : NULL;
+        if ( pShell.is() )
             if ( pWindow == pShell->GetWindow() || pShell->GetWindow()->IsChild( pWindow ) )
                 if ( pShell->HasMouseClickListeners_Impl() && pShell->HandleNotifyEvent_Impl( rNEvt ) )
                     return sal_True;
diff --git a/sfx2/source/view/ipclient.cxx b/sfx2/source/view/ipclient.cxx
index 19d61a5..d882756 100644
--- a/sfx2/source/view/ipclient.cxx
+++ b/sfx2/source/view/ipclient.cxx
@@ -857,7 +857,7 @@
 {
     for ( SfxViewFrame* pFrame = SfxViewFrame::GetFirst(pDoc); pFrame; pFrame=SfxViewFrame::GetNext(*pFrame,pDoc) )
     {
-        if( pFrame->GetViewShell() )
+        if( pFrame->GetViewShell().is() )
         {
             SfxInPlaceClient* pClient = pFrame->GetViewShell()->FindIPClient( xObject, NULL );
             if ( pClient )
diff --git a/sfx2/source/view/sfxbasecontroller.cxx b/sfx2/source/view/sfxbasecontroller.cxx
index 31dfd3d..4206f5a 100644
--- a/sfx2/source/view/sfxbasecontroller.cxx
+++ b/sfx2/source/view/sfxbasecontroller.cxx
@@ -357,8 +357,8 @@
     throw (RuntimeException, util::CloseVetoException)
 {
     SolarMutexGuard aGuard;
-    SfxViewShell* pShell = m_pController->GetViewShell_Impl();
-    if  ( m_pController !=  NULL &&  pShell )
+    rtl::Reference< SfxViewShell > pShell = m_pController->GetViewShell_Impl();
+    if  ( m_pController !=  NULL &&  pShell.is() )
     {
         sal_Bool bCanClose = (sal_Bool) pShell->PrepareClose( sal_False );
         if ( !bCanClose )
@@ -395,7 +395,7 @@
     ::cppu::OMultiTypeInterfaceContainerHelper      m_aListenerContainer    ;
     ::cppu::OInterfaceContainerHelper               m_aInterceptorContainer ;
     Reference< XStatusIndicator >           m_xIndicator            ;
-    SfxViewShell*                           m_pViewShell            ;
+    rtl::Reference< SfxViewShell >          m_pViewShell            ;
     SfxBaseController*                      m_pController           ;
     bool                                    m_bDisposing            ;
     sal_Bool                                m_bSuspendState         ;
@@ -403,7 +403,7 @@
     Sequence< PropertyValue >               m_aCreationArgs         ;
 
     IMPL_SfxBaseController_DataContainer(   ::osl::Mutex&              aMutex      ,
-                                            SfxViewShell*       pViewShell  ,
+                                            rtl::Reference< SfxViewShell > pViewShell  ,
                                             SfxBaseController*  pController )
             :   m_xListener                     ( new IMPL_SfxBaseController_ListenerHelper( pController ) )
             ,   m_xCloseListener                ( new IMPL_SfxBaseController_CloseListenerHelper( pController ) )
@@ -439,10 +439,10 @@
 void SAL_CALL IMPL_SfxBaseController_ListenerHelper::frameAction( const frame::FrameActionEvent& aEvent ) throw( RuntimeException )
 {
     SolarMutexGuard aGuard;
-    if  (
-            ( m_pController !=  NULL ) &&
-            ( aEvent.Frame  ==  m_pController->getFrame() ) &&
-            ( m_pController->GetViewShell_Impl() && m_pController->GetViewShell_Impl()->GetWindow() !=  NULL                                                    )
+    if  ( m_pController !=  NULL &&
+          aEvent.Frame  ==  m_pController->getFrame() &&
+          m_pController->GetViewShell_Impl().is() &&
+          m_pController->GetViewShell_Impl()->GetWindow() !=  NULL
         )
     {
         if ( aEvent.Action == frame::FrameAction_FRAME_UI_ACTIVATED )
@@ -472,7 +472,7 @@
 //  SfxBaseController -> constructor
 //________________________________________________________________________________________________________
 DBG_NAME(sfx2_SfxBaseController)
-SfxBaseController::SfxBaseController( SfxViewShell* pViewShell )
+SfxBaseController::SfxBaseController( rtl::Reference< SfxViewShell > pViewShell )
     :   m_pData ( new IMPL_SfxBaseController_DataContainer( m_aMutex, pViewShell, this ))
 {
     DBG_CTOR(sfx2_SfxBaseController,NULL);
@@ -496,7 +496,7 @@
 Reference< XWindow > SAL_CALL SfxBaseController::getComponentWindow() throw (RuntimeException)
 {
     SolarMutexGuard aGuard;
-    if ( !m_pData->m_pViewShell )
+    if ( !m_pData->m_pViewShell.is() )
         throw DisposedException();
 
     return Reference< XWindow >( GetViewFrame_Impl().GetFrame().GetWindow().GetComponentInterface(), UNO_QUERY_THROW );
@@ -505,7 +505,7 @@
 OUString SAL_CALL SfxBaseController::getViewControllerName() throw (RuntimeException)
 {
     SolarMutexGuard aGuard;
-    if ( !m_pData->m_pViewShell || !m_pData->m_pViewShell->GetObjectShell() )
+    if ( !m_pData->m_pViewShell.is() || !m_pData->m_pViewShell->GetObjectShell() )
         throw DisposedException();
 
     const SfxObjectFactory& rDocFac( m_pData->m_pViewShell->GetObjectShell()->GetFactory() );
@@ -522,7 +522,7 @@
 Sequence< PropertyValue > SAL_CALL SfxBaseController::getCreationArguments() throw (RuntimeException)
 {
     SolarMutexGuard aGuard;
-    if ( !m_pData->m_pViewShell || !m_pData->m_pViewShell->GetObjectShell() )
+    if ( !m_pData->m_pViewShell.is() || !m_pData->m_pViewShell->GetObjectShell() )
         throw DisposedException();
 
     return m_pData->m_aCreationArgs;
@@ -536,7 +536,7 @@
 
 SfxViewFrame& SfxBaseController::GetViewFrame_Impl() const
 {
-    ENSURE_OR_THROW( m_pData->m_pViewShell, "not to be called without a view shell" );
+    ENSURE_OR_THROW( m_pData->m_pViewShell.is(), "not to be called without a view shell" );
     SfxViewFrame* pActFrame = m_pData->m_pViewShell->GetFrame();
     ENSURE_OR_THROW( pActFrame, "a view shell without a view frame is pretty pathological" );
     return *pActFrame;
@@ -568,7 +568,7 @@
         if ( xCloseable.is() )
             xCloseable->addCloseListener( m_pData->m_xCloseListener );
 
-        if ( m_pData->m_pViewShell )
+        if ( m_pData->m_pViewShell.is() )
         {
             ConnectSfxFrame_Impl( E_CONNECT );
             ShowInfoBars( );
@@ -586,7 +586,7 @@
 
 sal_Bool SAL_CALL SfxBaseController::attachModel( const Reference< frame::XModel >& xModel ) throw( RuntimeException )
 {
-    if ( m_pData->m_pViewShell && xModel.is() && xModel != m_pData->m_pViewShell->GetObjectShell()->GetModel() )
+    if ( m_pData->m_pViewShell.is() && xModel.is() && xModel != m_pData->m_pViewShell->GetObjectShell()->GetModel() )
     {
         // don't allow to reattach a model!
         OSL_FAIL("Can't reattach model!");
@@ -613,7 +613,7 @@
 
     if ( bSuspend == sal_True )
     {
-        if ( !m_pData->m_pViewShell )
+        if ( !m_pData->m_pViewShell.is() )
         {
             m_pData->m_bSuspendState = sal_True;
             return sal_True;
@@ -647,7 +647,7 @@
         if ( getFrame().is() )
             getFrame()->addFrameActionListener( m_pData->m_xListener ) ;
 
-        if ( m_pData->m_pViewShell )
+        if ( m_pData->m_pViewShell.is() )
         {
             ConnectSfxFrame_Impl( E_RECONNECT );
         }
@@ -666,7 +666,7 @@
     uno::Any         aAny;
     OUString sData;
     SolarMutexGuard aGuard;
-    if ( m_pData->m_pViewShell )
+    if ( m_pData->m_pViewShell.is() )
     {
         m_pData->m_pViewShell->WriteUserData( sData ) ;
         aAny <<= sData ;
@@ -682,7 +682,7 @@
 void SAL_CALL SfxBaseController::restoreViewData( const uno::Any& aValue ) throw( RuntimeException )
 {
     SolarMutexGuard aGuard;
-    if ( m_pData->m_pViewShell )
+    if ( m_pData->m_pViewShell.is() )
     {
         OUString sData;
         aValue >>= sData ;
@@ -707,7 +707,7 @@
 Reference< frame::XModel > SAL_CALL SfxBaseController::getModel() throw( RuntimeException )
 {
     SolarMutexGuard aGuard;
-    return m_pData->m_pViewShell ? m_pData->m_pViewShell->GetObjectShell()->GetModel() : Reference < frame::XModel > () ;
+    return m_pData->m_pViewShell.is() ? m_pData->m_pViewShell->GetObjectShell()->GetModel() : Reference < frame::XModel > () ;
 }
 
 //________________________________________________________________________________________________________
@@ -720,7 +720,7 @@
 {
     SolarMutexGuard aGuard;
     Reference< frame::XDispatch >  xDisp;
-    if ( m_pData->m_pViewShell )
+    if ( m_pData->m_pViewShell.is() )
     {
         SfxViewFrame*           pAct    = m_pData->m_pViewShell->GetViewFrame() ;
         if ( !m_pData->m_bDisposing )
@@ -899,7 +899,7 @@
     frame::BorderWidths aResult;
 
     SolarMutexGuard aGuard;
-    if ( m_pData->m_pViewShell )
+    if ( m_pData->m_pViewShell.is() )
     {
         SvBorder aBorder = m_pData->m_pViewShell->GetBorderPixel();
         aResult.Left = aBorder.Left();
@@ -929,7 +929,7 @@
     throw ( RuntimeException )
 {
     SolarMutexGuard aGuard;
-    if ( m_pData->m_pViewShell )
+    if ( m_pData->m_pViewShell.is() )
     {
         Rectangle aTmpRect = VCLRectangle( aPreliminaryRectangle );
         m_pData->m_pViewShell->QueryObjAreaPixel( aTmpRect );
@@ -980,7 +980,7 @@
     if ( m_pData->m_pController && m_pData->m_pController->getFrame().is() )
         m_pData->m_pController->getFrame()->removeFrameActionListener( m_pData->m_xListener ) ;
 
-    if ( m_pData->m_pViewShell )
+    if ( m_pData->m_pViewShell.is() )
     {
         SfxViewFrame* pFrame = m_pData->m_pViewShell->GetViewFrame() ;
         if ( pFrame && pFrame->GetViewShell() == m_pData->m_pViewShell )
@@ -1020,9 +1020,9 @@
             attachFrame( aXFrame );
 
             m_pData->m_xListener->disposing( aObject );
-            SfxViewShell *pShell = m_pData->m_pViewShell;
-            m_pData->m_pViewShell = NULL;
-            if ( pFrame->GetViewShell() == pShell )
+            rtl::Reference< SfxViewShell > pShell = m_pData->m_pViewShell;
+            m_pData->m_pViewShell.clear();
+            if ( pFrame->GetViewShell().get() == pShell.get() )
             {
                 // Enter registrations only allowed if we are the owner!
                 if ( pFrame->GetFrame().OwnsBindings_Impl() )
@@ -1055,7 +1055,7 @@
 void SfxBaseController::ReleaseShell_Impl()
 {
     SolarMutexGuard aGuard;
-    if ( m_pData->m_pViewShell )
+    if ( m_pData->m_pViewShell.is() )
     {
         SfxObjectShell* pDoc = m_pData->m_pViewShell->GetObjectShell() ;
         Reference< frame::XModel > xModel = pDoc->GetModel();
@@ -1066,14 +1066,14 @@
             if ( xCloseable.is() )
                 xCloseable->removeCloseListener( m_pData->m_xCloseListener );
         }
-        m_pData->m_pViewShell = 0;
+        m_pData->m_pViewShell.clear();
 
         Reference < frame::XFrame > aXFrame;
         attachFrame( aXFrame );
     }
 }
 
-SfxViewShell* SfxBaseController::GetViewShell_Impl() const
+rtl::Reference< SfxViewShell > SfxBaseController::GetViewShell_Impl() const
 {
     return m_pData->m_pViewShell;
 }
@@ -1081,7 +1081,7 @@
 Reference< task::XStatusIndicator > SAL_CALL SfxBaseController::getStatusIndicator(  ) throw (RuntimeException)
 {
     SolarMutexGuard aGuard;
-    if ( m_pData->m_pViewShell && !m_pData->m_xIndicator.is() )
+    if ( m_pData->m_pViewShell.is() && !m_pData->m_xIndicator.is() )
         m_pData->m_xIndicator = new SfxStatusIndicator( this, m_pData->m_pViewShell->GetViewFrame()->GetFrame().GetWorkWindow_Impl() );
     return m_pData->m_xIndicator;
 }
@@ -1092,7 +1092,7 @@
     m_pData->m_aInterceptorContainer.addInterface( xInterceptor );
 
     SolarMutexGuard aGuard;
-    if ( m_pData->m_pViewShell )
+    if ( m_pData->m_pViewShell.is() )
         m_pData->m_pViewShell->AddContextMenuInterceptor_Impl( xInterceptor );
 }
 
@@ -1102,7 +1102,7 @@
     m_pData->m_aInterceptorContainer.removeInterface( xInterceptor );
 
     SolarMutexGuard aGuard;
-    if ( m_pData->m_pViewShell )
+    if ( m_pData->m_pViewShell.is() )
         m_pData->m_pViewShell->RemoveContextMenuInterceptor_Impl( xInterceptor );
 }
 
@@ -1170,7 +1170,7 @@
     std::list< frame::DispatchInformation > aCmdList;
 
     SolarMutexGuard aGuard;
-    if ( m_pData->m_pViewShell )
+    if ( m_pData->m_pViewShell.is() )
     {
         const sal_uIntPtr nMode( SFX_SLOT_TOOLBOXCONFIG|SFX_SLOT_ACCELCONFIG|SFX_SLOT_MENUCONFIG );
 
@@ -1229,7 +1229,7 @@
 
 void SfxBaseController::ConnectSfxFrame_Impl( const ConnectSfxFrame i_eConnect )
 {
-    ENSURE_OR_THROW( m_pData->m_pViewShell, "not to be called without a view shell" );
+    ENSURE_OR_THROW( m_pData->m_pViewShell.is(), "not to be called without a view shell" );
     SfxViewFrame* pViewFrame = m_pData->m_pViewShell->GetFrame();
     ENSURE_OR_THROW( pViewFrame, "a view shell without a view frame is pretty pathological" );
 
@@ -1420,7 +1420,7 @@
 
 void SfxBaseController::ShowInfoBars( )
 {
-    if ( m_pData->m_pViewShell )
+    if ( m_pData->m_pViewShell.is() )
     {
         // CMIS verifications
         Reference< document::XCmisDocument > xCmisDoc( m_pData->m_pViewShell->GetObjectShell()->GetModel(), uno::UNO_QUERY );
@@ -1464,7 +1464,7 @@
 
 IMPL_LINK_NOARG ( SfxBaseController, CheckOutHandler )
 {
-    if ( m_pData->m_pViewShell )
+    if ( m_pData->m_pViewShell.is() )
         m_pData->m_pViewShell->GetObjectShell()->CheckOut( );
     return 0;
 }
diff --git a/sfx2/source/view/viewfac.cxx b/sfx2/source/view/viewfac.cxx
index a3e2f58..d5b74eb 100644
--- a/sfx2/source/view/viewfac.cxx
+++ b/sfx2/source/view/viewfac.cxx
@@ -20,15 +20,16 @@
 #include <sfx2/app.hxx>
 #include "sfx2/viewfac.hxx"
 #include <rtl/ustrbuf.hxx>
+#include <sfx2/viewsh.hxx>
 
 // STATIC DATA -----------------------------------------------------------
 
 DBG_NAME(SfxViewFactory)
 
-SfxViewShell *SfxViewFactory::CreateInstance(SfxViewFrame *pFrame, SfxViewShell *pOldSh )
+rtl::Reference< SfxViewShell > SfxViewFactory::CreateInstance(SfxViewFrame *pFrame, rtl::Reference< SfxViewShell > pOldSh )
 {
     DBG_CHKTHIS(SfxViewFactory, 0);
-    return (*fnCreate)(pFrame, pOldSh);
+    return (*fnCreate)(pFrame, pOldSh.get());
 }
 
 OUString SfxViewFactory::GetLegacyViewName() const
diff --git a/sfx2/source/view/viewfrm.cxx b/sfx2/source/view/viewfrm.cxx
index ccd7d98..e515d33 100644
--- a/sfx2/source/view/viewfrm.cxx
+++ b/sfx2/source/view/viewfrm.cxx
@@ -955,7 +955,7 @@
                 break;
         }
     }
-    else if ( GetViewShell() )
+    else if ( GetViewShell().is() )
     {
         // The SW has its own undo in the View
         const SfxPoolItem *pRet = GetViewShell()->ExecuteSlot( rReq );
@@ -981,8 +981,8 @@
     {
         // The SW has its own undo in the View
         SfxWhichIter aIter( rSet );
-        SfxViewShell *pViewSh = GetViewShell();
-        if( !pViewSh ) return;
+        rtl::Reference< SfxViewShell > pViewSh = GetViewShell();
+        if( !pViewSh.is() ) return;
         for ( sal_uInt16 nSID = aIter.FirstWhich(); nSID; nSID = aIter.NextWhich() )
             pViewSh->GetSlotState( nSID, 0, &rSet );
         return;
@@ -1075,13 +1075,13 @@
         GetWindow().GrabFocus();
     }
 
-    SfxViewShell *pDyingViewSh = GetViewShell();
-    if ( pDyingViewSh )
+    rtl::Reference< SfxViewShell > pDyingViewSh = GetViewShell();
+    if ( pDyingViewSh.is() )
     {
         PopShellAndSubShells_Impl( *pDyingViewSh );
         pDyingViewSh->DisconnectAllClients();
         SetViewShell_Impl(0);
-        delete pDyingViewSh;
+        pDyingViewSh->dispose();
     }
 #ifdef DBG_UTIL
     else
@@ -1126,7 +1126,7 @@
 
     // If no saving have been made up until now, then embedded Objects should
     // not be saved automatically anymore.
-    if ( GetViewShell() )
+    if ( GetViewShell().is() )
         GetViewShell()->DiscardClients_Impl();
     Broadcast( SfxSimpleHint( SFX_HINT_DYING ) );
 
@@ -1186,19 +1186,19 @@
 }
 
 //------------------------------------------------------------------------
-void SfxViewFrame::InvalidateBorderImpl( const SfxViewShell* pSh )
+void SfxViewFrame::InvalidateBorderImpl( const SfxViewShell *pSh )
 {
     if( pSh && !nAdjustPosPixelLock )
     {
-        if ( GetViewShell() && GetWindow().IsVisible() )
+        if ( GetViewShell().is() && GetWindow().IsVisible() )
         {
             if ( GetFrame().IsInPlace() )
             {
                 return;
             }
 
-            DoAdjustPosSizePixel( (SfxViewShell *) GetViewShell(), Point(),
-                                            GetWindow().GetOutputSizePixel() );
+            DoAdjustPosSizePixel( GetViewShell(), Point(),
+                                  GetWindow().GetOutputSizePixel() );
         }
     }
 }
@@ -1206,7 +1206,7 @@
 //------------------------------------------------------------------------
 sal_Bool SfxViewFrame::SetBorderPixelImpl
 (
-    const SfxViewShell* pVSh,
+    const SfxViewShell *pVSh,
     const SvBorder&     rBorder
 )
 
@@ -1249,7 +1249,7 @@
 //------------------------------------------------------------------------
 const SvBorder& SfxViewFrame::GetBorderPixelImpl
 (
-    const SfxViewShell* /*pSh*/
+    const SfxViewShell */*pSh*/
 )   const
 
 {
@@ -1590,7 +1590,7 @@
 //--------------------------------------------------------------------
 void SfxViewFrame::DoAdjustPosSizePixel //! divide on Inner.../Outer...
 (
-    SfxViewShell*   pSh,
+    rtl::Reference< SfxViewShell > pSh,
     const Point&    rPos,
     const Size&     rSize
 )
@@ -1598,7 +1598,7 @@
     DBG_CHKTHIS(SfxViewFrame, 0);
 
     // Components do not use this Method!
-    if( pSh && pSh->GetWindow() && !nAdjustPosPixelLock )
+    if( pSh.is() && pSh->GetWindow() && !nAdjustPosPixelLock )
     {
         nAdjustPosPixelLock++;
         if ( pImp->bResizeInToOut )
@@ -1629,7 +1629,7 @@
 }
 
 //--------------------------------------------------------------------
-void SfxViewFrame::SetViewShell_Impl( SfxViewShell *pVSh )
+void SfxViewFrame::SetViewShell_Impl( rtl::Reference< SfxViewShell > pVSh )
 
 /*  [Description]
 
@@ -1641,7 +1641,7 @@
     SfxShell::SetViewShell_Impl( pVSh );
 
     // Hack: InPlaceMode
-    if ( pVSh )
+    if ( pVSh.is() )
         pImp->bResizeInToOut = sal_False;
 }
 
@@ -1702,19 +1702,10 @@
         }
 
         // cursor and focus
-        SfxViewShell* pViewSh = GetViewShell();
-        if ( bEnable )
-        {
-            // show cursor
-            if ( pViewSh )
-                pViewSh->ShowCursor();
-        }
-        else
-        {
-            // hide cursor
-            if ( pViewSh )
-                pViewSh->ShowCursor(sal_False);
-        }
+        rtl::Reference< SfxViewShell > pViewSh = GetViewShell();
+        // show/hide cursor
+        if ( pViewSh.is() )
+            pViewSh->ShowCursor(bEnable);
     }
 }
 
@@ -1773,52 +1764,46 @@
 //--------------------------------------------------------------------
 void SfxViewFrame::MakeActive_Impl( sal_Bool bGrabFocus )
 {
-    if ( GetViewShell() && !GetFrame().IsClosing_Impl() )
+    if ( GetViewShell().is() && !GetFrame().IsClosing_Impl() && IsVisible() )
     {
-        if ( IsVisible() )
+        sal_Bool bPreview = sal_False;
+        if ( GetObjectShell()->IsPreview() )
         {
-            if ( GetViewShell() )
+            bPreview = sal_True;
+        }
+        else
+        {
+            SfxViewFrame* pParent = GetParentViewFrame();
+            if ( pParent )
+                pParent->SetActiveChildFrame_Impl( this );
+        }
+
+        SfxViewFrame* pCurrent = SfxViewFrame::Current();
+        css::uno::Reference< css::frame::XFrame > xFrame = GetFrame().GetFrameInterface();
+        if ( !bPreview )
+        {
+            SetViewFrame( this );
+            GetBindings().SetActiveFrame( css::uno::Reference< css::frame::XFrame >() );
+            uno::Reference< frame::XFramesSupplier > xSupp( xFrame, uno::UNO_QUERY );
+            if ( xSupp.is() )
+                xSupp->setActiveFrame( uno::Reference < frame::XFrame >() );
+
+            css::uno::Reference< css::awt::XWindow > xContainerWindow = xFrame->getContainerWindow();
+            Window* pWindow = VCLUnoHelper::GetWindow(xContainerWindow);
+            if (pWindow && pWindow->HasChildPathFocus() && bGrabFocus)
             {
-                sal_Bool bPreview = sal_False;
-                if ( GetObjectShell()->IsPreview() )
-                {
-                    bPreview = sal_True;
-                }
-                else
-                {
-                    SfxViewFrame* pParent = GetParentViewFrame();
-                    if ( pParent )
-                        pParent->SetActiveChildFrame_Impl( this );
-                }
-
-                SfxViewFrame* pCurrent = SfxViewFrame::Current();
-                css::uno::Reference< css::frame::XFrame > xFrame = GetFrame().GetFrameInterface();
-                if ( !bPreview )
-                {
-                    SetViewFrame( this );
-                    GetBindings().SetActiveFrame( css::uno::Reference< css::frame::XFrame >() );
-                    uno::Reference< frame::XFramesSupplier > xSupp( xFrame, uno::UNO_QUERY );
-                    if ( xSupp.is() )
-                        xSupp->setActiveFrame( uno::Reference < frame::XFrame >() );
-
-                    css::uno::Reference< css::awt::XWindow > xContainerWindow = xFrame->getContainerWindow();
-                    Window* pWindow = VCLUnoHelper::GetWindow(xContainerWindow);
-                    if (pWindow && pWindow->HasChildPathFocus() && bGrabFocus)
-                    {
-                        SfxInPlaceClient *pCli = GetViewShell()->GetUIActiveClient();
-                        if ( ( !pCli || !pCli->IsObjectUIActive() ) &&
-                            ( !pCurrent || pCurrent->GetParentViewFrame_Impl() != this ) )
-                                GetFrame().GrabFocusOnComponent_Impl();
-                    }
-                }
-                else
-                {
-                    GetBindings().SetDispatcher( GetDispatcher() );
-                    GetBindings().SetActiveFrame( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > () );
-                    GetDispatcher()->Update_Impl( sal_False );
-                }
+                SfxInPlaceClient *pCli = GetViewShell()->GetUIActiveClient();
+                if ( ( !pCli || !pCli->IsObjectUIActive() ) &&
+                     ( !pCurrent || pCurrent->GetParentViewFrame_Impl() != this ) )
+                    GetFrame().GrabFocusOnComponent_Impl();
             }
         }
+        else
+        {
+            GetBindings().SetDispatcher( GetDispatcher() );
+            GetBindings().SetActiveFrame( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > () );
+            GetDispatcher()->Update_Impl( sal_False );
+        }
     }
 }
 
@@ -1869,7 +1854,7 @@
 {
     Reference< XFrame > xFrame( i_rFrame );
     bool bOwnFrame = false;
-    SfxViewShell* pSuccessView = NULL;
+    rtl::Reference< SfxViewShell > pSuccessView = NULL;
     try
     {
         if ( !xFrame.is() )
@@ -1916,7 +1901,7 @@
         DBG_UNHANDLED_EXCEPTION();
     }
 
-    if ( pSuccessView )
+    if ( pSuccessView.is() )
         return pSuccessView->GetViewFrame();
 
     if ( bOwnFrame )
@@ -1935,7 +1920,7 @@
 }
 
 //--------------------------------------------------------------------
-SfxViewShell* SfxViewFrame::LoadViewIntoFrame_Impl( const SfxObjectShell& i_rDoc, const Reference< XFrame >& i_rFrame,
+rtl::Reference< SfxViewShell > SfxViewFrame::LoadViewIntoFrame_Impl( const SfxObjectShell& i_rDoc, const Reference< XFrame >& i_rFrame,
                                            const Sequence< PropertyValue >& i_rLoadArgs, const sal_uInt16 i_nViewId,
                                            const bool i_bHidden )
 {
@@ -1958,8 +1943,8 @@
     xLoader->loadComponentFromURL( sURL, OUString("_self"), 0,
         aTransformLoadArgs.getPropertyValues() );
 
-    SfxViewShell* pViewShell = SfxViewShell::Get( i_rFrame->getController() );
-    ENSURE_OR_THROW( pViewShell,
+    rtl::Reference< SfxViewShell > pViewShell = SfxViewShell::Get( i_rFrame->getController() );
+    ENSURE_OR_THROW( pViewShell.is(),
         "SfxViewFrame::LoadViewIntoFrame_Impl: loading an SFX doc into a frame resulted in a non-SFX view - quite impossible" );
     return pViewShell;
 }
@@ -2044,7 +2029,7 @@
 
 void SfxViewFrame::SaveCurrentViewData_Impl( const sal_uInt16 i_nNewViewId )
 {
-    SfxViewShell* pCurrentShell = GetViewShell();
+    rtl::Reference< SfxViewShell > pCurrentShell = GetViewShell();
     ENSURE_OR_RETURN_VOID( pCurrentShell != NULL, "SfxViewFrame::SaveCurrentViewData_Impl: no current view shell -> no current view data!" );
 
     // determine the logical (API) view name
@@ -2148,9 +2133,9 @@
         ENSURE_OR_THROW( GetObjectShell() != NULL, "not possible without a document" );
 
         // if we already have a view shell, remove it
-        SfxViewShell* pOldSh = GetViewShell();
-        OSL_PRECOND( pOldSh, "SfxViewFrame::SwitchToViewShell_Impl: that's called *switch* (not for *initial-load*) for a reason" );
-        if ( pOldSh )
+        rtl::Reference< SfxViewShell > pOldSh = GetViewShell();
+        OSL_PRECOND( pOldSh.is(), "SfxViewFrame::SwitchToViewShell_Impl: that's called *switch* (not for *initial-load*) for a reason" );
+        if ( pOldSh.is() )
         {
             // ask whether it can be closed
             if ( !pOldSh->PrepareClose( sal_True ) )
@@ -2171,7 +2156,7 @@
         SaveCurrentViewData_Impl( nViewId );
 
         // create and load new ViewShell
-        SfxViewShell* pNewSh = LoadViewIntoFrame_Impl(
+        rtl::Reference< SfxViewShell > pNewSh = LoadViewIntoFrame_Impl(
             *GetObjectShell(),
             GetFrame().GetFrameInterface(),
             Sequence< PropertyValue >(),    // means "reuse existing model's args"
@@ -2186,7 +2171,7 @@
             DoAdjustPosSizePixel( pNewSh, Point(), GetWindow().GetOutputSizePixel() );
 
         GetBindings().LEAVEREGISTRATIONS();
-        delete pOldSh;
+        pOldSh->dispose();
     }
     catch ( const com::sun::star::uno::Exception& )
     {
@@ -2228,7 +2213,7 @@
     DBG_CHKTHIS(SfxViewFrame, 0);
 
     // If the Shells are just being replaced...
-    if ( !GetObjectShell() || !GetViewShell() )
+    if ( !GetObjectShell() || !GetViewShell().is() )
         return;
 
     switch ( rReq.GetSlot() )
@@ -2303,8 +2288,8 @@
         {
             SFX_REQUEST_ARG( rReq, pItem, SfxUInt16Item, SID_OBJECT, sal_False );
 
-            SfxViewShell *pViewShell = GetViewShell();
-            if ( pViewShell && pItem )
+            rtl::Reference< SfxViewShell > pViewShell = GetViewShell();
+            if ( pViewShell.is() && pItem )
             {
                 pViewShell->DoVerb( pItem->GetValue() );
                 rReq.Done();
@@ -2512,8 +2497,8 @@
     if ( bForce || aSize != pImp->aSize )
     {
         pImp->aSize = aSize;
-        SfxViewShell *pShell = GetViewShell();
-        if ( pShell )
+        rtl::Reference< SfxViewShell > pShell = GetViewShell();
+        if ( pShell.is() )
         {
             if ( GetFrame().IsInPlace() )
             {
@@ -2744,7 +2729,9 @@
         }
 
         // #i17355# update the Basic IDE
-        for ( SfxViewShell* pViewShell = SfxViewShell::GetFirst(); pViewShell; pViewShell = SfxViewShell::GetNext( *pViewShell ) )
+        for ( rtl::Reference< SfxViewShell > pViewShell = SfxViewShell::GetFirst();
+              pViewShell.is();
+              pViewShell = SfxViewShell::GetNext( *pViewShell ) )
         {
             if ( pViewShell->GetName() == "BasicIDE" )
             {
diff --git a/sfx2/source/view/viewfrm2.cxx b/sfx2/source/view/viewfrm2.cxx
index 5c84445..11b5477 100644
--- a/sfx2/source/view/viewfrm2.cxx
+++ b/sfx2/source/view/viewfrm2.cxx
@@ -157,7 +157,7 @@
 void SfxViewFrame::Exec_Impl(SfxRequest &rReq )
 {
     // If presently the shells are replaced...
-    if ( !GetObjectShell() || !GetViewShell() )
+    if ( !GetObjectShell() || !GetViewShell().is() )
         return;
 
     switch ( rReq.GetSlot() )
@@ -321,7 +321,7 @@
                 break;
 
             case SID_OBJECT:
-                if ( GetViewShell() && GetViewShell()->GetVerbs().getLength() && !GetObjectShell()->IsInPlaceActive() )
+                if ( GetViewShell().is() && GetViewShell()->GetVerbs().getLength() && !GetObjectShell()->IsInPlaceActive() )
                 {
                     uno::Any aAny;
                     aAny <<= GetViewShell()->GetVerbs();
@@ -393,7 +393,7 @@
 
 void SfxViewFrame::Activate( sal_Bool bMDI )
 {
-    DBG_ASSERT(GetViewShell(), "No Shell");
+    DBG_ASSERT(GetViewShell().is(), "No Shell");
     if ( bMDI )
         pImp->bActive = sal_True;
 //(mba): here maybe as in Beanframe NotifyEvent ?!
@@ -401,7 +401,7 @@
 
 void SfxViewFrame::Deactivate( sal_Bool bMDI )
 {
-    DBG_ASSERT(GetViewShell(), "No Shell");
+    DBG_ASSERT(GetViewShell().is(), "No Shell");
     if ( bMDI )
         pImp->bActive = sal_False;
 //(mba): here maybe as in Beanframe NotifyEvent ?!
diff --git a/sfx2/source/view/viewsh.cxx b/sfx2/source/view/viewsh.cxx
index 8ad205d..f680967 100644
--- a/sfx2/source/view/viewsh.cxx
+++ b/sfx2/source/view/viewsh.cxx
@@ -96,7 +96,7 @@
     datatransfer::clipboard::XClipboardListener >
 {
 public:
-    SfxClipboardChangeListener( SfxViewShell* pView, const uno::Reference< datatransfer::clipboard::XClipboardNotifier >& xClpbrdNtfr );
+    SfxClipboardChangeListener( rtl::Reference< SfxViewShell > pView, const uno::Reference< datatransfer::clipboard::XClipboardNotifier >& xClpbrdNtfr );
     virtual ~SfxClipboardChangeListener();
 
     // XEventListener
@@ -127,14 +127,14 @@
     };
 
 private:
-    SfxViewShell* m_pViewShell;
+    rtl::Reference< SfxViewShell > m_pViewShell;
     uno::Reference< datatransfer::clipboard::XClipboardNotifier > m_xClpbrdNtfr;
     uno::Reference< lang::XComponent > m_xCtrl;
 
     DECL_STATIC_LINK( SfxClipboardChangeListener, AsyncExecuteHdl_Impl, AsyncExecuteInfo* );
 };
 
-SfxClipboardChangeListener::SfxClipboardChangeListener( SfxViewShell* pView, const uno::Reference< datatransfer::clipboard::XClipboardNotifier >& xClpbrdNtfr )
+SfxClipboardChangeListener::SfxClipboardChangeListener( rtl::Reference< SfxViewShell > pView, const uno::Reference< datatransfer::clipboard::XClipboardNotifier >& xClpbrdNtfr )
   : m_pViewShell( 0 ), m_xClpbrdNtfr( xClpbrdNtfr )
 {
     m_xCtrl = uno::Reference < lang::XComponent >( pView->GetController(), uno::UNO_QUERY );
@@ -157,7 +157,7 @@
 void SfxClipboardChangeListener::ChangedContents()
 {
     const SolarMutexGuard aGuard;
-    if( m_pViewShell )
+    if( m_pViewShell.is() )
     {
         SfxBindings& rBind = m_pViewShell->GetViewFrame()->GetBindings();
         rBind.Invalidate( SID_PASTE );
@@ -734,7 +734,7 @@
                 if ( pTopFrame != &GetFrame()->GetFrame() )
                 {
                     // FramesetDocument
-                    SfxViewShell *pShell = pTopFrame->GetCurrentViewFrame()->GetViewShell();
+                    rtl::Reference< SfxViewShell > pShell = pTopFrame->GetCurrentViewFrame()->GetViewShell();
                     if ( pShell->GetInterface()->GetSlot( nId ) )
                         pShell->ExecuteSlot( rReq );
                     break;
@@ -745,8 +745,8 @@
                 {
                     if ( pTopFrame->GetCurrentViewFrame() )
                     {
-                        SfxViewShell *pView = pTopFrame->GetCurrentViewFrame()->GetViewShell();
-                        if ( pView )
+                        rtl::Reference< SfxViewShell > pView = pTopFrame->GetCurrentViewFrame()->GetViewShell();
+                        if ( pView.is() )
                         {
                             pView->pImp->m_bPlugInsActive = bActive;
                             Rectangle aVisArea = GetObjectShell()->GetVisArea();
@@ -1263,7 +1263,7 @@
     DBG_DTOR(SfxViewShell, 0);
 
     // Remove from list
-    const SfxViewShell *pThis = this;
+    const SfxViewShell *pThis (this);
     SfxViewShellArr_Impl &rViewArr = SFX_APP()->GetViewShells_Impl();
     SfxViewShellArr_Impl::iterator it = std::find( rViewArr.begin(), rViewArr.end(), pThis );
     rViewArr.erase( it );
@@ -1315,7 +1315,7 @@
 
 //--------------------------------------------------------------------
 
-SfxViewShell* SfxViewShell::Current()
+rtl::Reference< SfxViewShell > SfxViewShell::Current()
 {
     SfxViewFrame *pCurrent = SfxViewFrame::Current();
     return pCurrent ? pCurrent->GetViewShell() : NULL;
@@ -1323,13 +1323,13 @@
 
 //--------------------------------------------------------------------
 
-SfxViewShell* SfxViewShell::Get( const Reference< XController>& i_rController )
+rtl::Reference< SfxViewShell > SfxViewShell::Get( const Reference< XController>& i_rController )
 {
     if ( !i_rController.is() )
         return NULL;
 
-    for (   SfxViewShell* pViewShell = SfxViewShell::GetFirst( NULL, sal_False );
-            pViewShell;
+    for (   rtl::Reference< SfxViewShell > pViewShell = SfxViewShell::GetFirst( NULL, sal_False );
+            pViewShell.is();
             pViewShell = SfxViewShell::GetNext( *pViewShell, NULL, sal_False )
         )
     {
@@ -1490,7 +1490,7 @@
 //--------------------------------------------------------------------
 // returns the first shell of spec. type viewing the specified doc.
 
-SfxViewShell* SfxViewShell::GetFirst
+rtl::Reference< SfxViewShell > SfxViewShell::GetFirst
 (
     const TypeId* pType,
     sal_Bool          bOnlyVisible
@@ -1501,8 +1501,8 @@
     SfxViewFrameArr_Impl &rFrames = SFX_APP()->GetViewFrames_Impl();
     for ( sal_uInt16 nPos = 0; nPos < rShells.size(); ++nPos )
     {
-        SfxViewShell *pShell = rShells[nPos];
-        if ( pShell )
+        rtl::Reference< SfxViewShell > pShell = rShells[nPos];
+        if ( pShell.is() )
         {
             // sometimes dangling SfxViewShells exist that point to a dead SfxViewFrame
             // these ViewShells shouldn't be accessible anymore
@@ -1527,7 +1527,7 @@
 //--------------------------------------------------------------------
 // returns the next shell of spec. type viewing the specified doc.
 
-SfxViewShell* SfxViewShell::GetNext
+rtl::Reference< SfxViewShell > SfxViewShell::GetNext
 (
     const SfxViewShell& rPrev,
     const TypeId*       pType,
@@ -1543,8 +1543,8 @@
 
     for ( ++nPos; nPos < rShells.size(); ++nPos )
     {
-        SfxViewShell *pShell = rShells[nPos];
-        if ( pShell )
+        rtl::Reference< SfxViewShell > pShell = rShells[nPos];
+        if ( pShell.is() )
         {
             // sometimes dangling SfxViewShells exist that point to a dead SfxViewFrame
             // these ViewShells shouldn't be accessible anymore
@@ -1884,7 +1884,7 @@
 SfxInPlaceClientList* SfxViewShell::GetIPClientList_Impl( sal_Bool bCreate ) const
 {
     if ( !pIPClientList && bCreate )
-        ( (SfxViewShell*) this )->pIPClientList = new SfxInPlaceClientList;
+        const_cast< SfxViewShell* > (this)->pIPClientList = new SfxInPlaceClientList;
     return pIPClientList;
 }
 
@@ -1920,7 +1920,7 @@
     pImp->aInterceptorContainer.removeInterface( xInterceptor );
 }
 
-void Change( Menu* pMenu, SfxViewShell* pView )
+void Change( Menu* pMenu, rtl::Reference< SfxViewShell > pView )
 {
     SfxDispatcher *pDisp = pView->GetViewFrame()->GetDispatcher();
     sal_uInt16 nCount = pMenu->GetItemCount();
diff --git a/sw/source/ui/app/appenv.cxx b/sw/source/ui/app/appenv.cxx
index 63b614a6..1f4862a 100644
--- a/sw/source/ui/app/appenv.cxx
+++ b/sw/source/ui/app/appenv.cxx
@@ -144,7 +144,7 @@
 
     SwDocShell      *pMyDocSh;
     SfxViewFrame    *pFrame;
-    SwView          *pNewView;
+    rtl::Reference< SwView > pNewView;
     SwWrtShell      *pOldSh,
                     *pSh;
 
@@ -156,7 +156,13 @@
     SfxObjectShellLock xDocSh( new SwDocShell( SFX_CREATE_MODE_STANDARD ) );
     xDocSh->DoInitNew( 0 );
     pFrame = SfxViewFrame::LoadHiddenDocument( *xDocSh, 0 );
-    pNewView = (SwView*) pFrame->GetViewShell();
+#if OSL_DEBUG_LEVEL > 0
+    pNewView = dynamic_cast<SwView*>(pFrame->GetViewShell().get());
+    assert( (  pNewView.is() &&  pFrame->GetViewShell().is() ) ||
+            ( !pNewView.is() && !pFrame->GetViewShell().is() ));
+#else
+    pNewView = static_cast<SwView*>(pFrame->GetViewShell().get());
+#endif
     pNewView->AttrChangedNotify( &pNewView->GetWrtShell() ); // so that SelectShell is being called
     pSh = pNewView->GetWrtShellPtr();
 
diff --git a/sw/source/ui/app/apphdl.cxx b/sw/source/ui/app/apphdl.cxx
index 8582adb..8eec13f 100644
--- a/sw/source/ui/app/apphdl.cxx
+++ b/sw/source/ui/app/apphdl.cxx
@@ -101,6 +101,9 @@
 
 using namespace ::com::sun::star;
 
+// TODO: move to rtl/ref.hxx
+#define REF_CAST( T, pObj ) \
+    ( pObj.is() && (pObj)->IsA( TYPE(T) ) ? (static_cast<T*>(pObj.get())) : 0 )
 
 // Slotmaps for the application's methods
 
@@ -127,8 +130,8 @@
     SfxWhichIter aIter(rSet);
     sal_uInt16 nWhich = aIter.FirstWhich();
 
-    SwView* pActView = ::GetActiveView();
-    sal_Bool bWebView = 0 != PTR_CAST(SwWebView, pActView);
+    rtl::Reference< SwView > pActView = ::GetActiveView();
+    sal_Bool bWebView = 0 != REF_CAST(SwWebView, pActView);
 
     while(nWhich)
     {
@@ -139,8 +142,8 @@
             case FN_ENVELOP:
             {
                 bool bDisable = false;
-                SfxViewShell* pCurrView = SfxViewShell::Current();
-                if( !pCurrView || (pCurrView && !pCurrView->ISA(SwView)) )
+                rtl::Reference< SfxViewShell > pCurrView = SfxViewShell::Current();
+                if( !pCurrView.is() || !pCurrView->ISA(SwView) )
                     bDisable = true;
                 SwDocShell *pDocSh = (SwDocShell*) SfxObjectShell::Current();
                 if ( bDisable ||
@@ -157,7 +160,7 @@
                 {
                     SwWrtShell* pSh = 0;
                     int nSelection = 0;
-                    if( pActView )
+                    if( pActView.is() )
                         pSh = &pActView->GetWrtShell();
                     if( pSh )
                         nSelection = pSh->GetSelectionType();
@@ -181,9 +184,9 @@
     }
 }
 
-static SwView* lcl_LoadDoc(SwView* pView, const OUString& rURL)
+static rtl::Reference< SwView > lcl_LoadDoc(rtl::Reference< SwView > pView, const OUString& rURL)
 {
-    SwView* pNewView = 0;
+    rtl::Reference< SwView > pNewView = 0;
     if(!rURL.isEmpty())
     {
         SfxStringItem aURL(SID_FILE_NAME, rURL);
@@ -197,12 +200,12 @@
 
         if(pShell)
         {
-            SfxViewShell* pViewShell = pShell->GetViewShell();
-            if(pViewShell)
+            rtl::Reference< SfxViewShell > pViewShell = pShell->GetViewShell();
+            if(pViewShell.is())
             {
                 if( pViewShell->ISA(SwView) )
                 {
-                    pNewView = PTR_CAST(SwView,pViewShell);
+                    pNewView = REF_CAST(SwView,pViewShell);
                     pNewView->GetViewFrame()->GetFrame().Appear();
                 }
                 else
@@ -220,7 +223,7 @@
                                 SFX_CALLMODE_SYNCHRON, &aFactory, 0L);
         SfxFrame* pFrm = pItem ? pItem->GetFrame() : 0;
         SfxViewFrame* pFrame = pFrm ? pFrm->GetCurrentViewFrame() : 0;
-        pNewView = pFrame ? PTR_CAST(SwView, pFrame->GetViewShell()) : 0;
+        pNewView = pFrame ? REF_CAST(SwView, pFrame->GetViewShell()) : 0;
     }
 
     return pNewView;
@@ -234,8 +237,8 @@
 
 class SwMailMergeWizardExecutor : public salhelper::SimpleReferenceObject
 {
-    SwView*                  m_pView;       // never owner
-    SwView*                  m_pView2Close; // never owner
+    rtl::Reference< SwView >                  m_pView;       // never owner
+    rtl::Reference< SwView >                  m_pView2Close; // never owner
     SwMailMergeConfigItem*   m_pMMConfig;   // sometimes owner
     AbstractMailMergeWizard* m_pWizard;     // always owner
 
@@ -271,15 +274,15 @@
 
 void SwMailMergeWizardExecutor::ExecuteMailMergeWizard( const SfxItemSet * pArgs )
 {
-    if ( m_pView )
+    if ( m_pView.is() )
     {
         OSL_FAIL("SwMailMergeWizardExecutor::ExecuteMailMergeWizard: Already executing the wizard!" );
         return;
     }
 
     m_pView = ::GetActiveView(); // not owner!
-    OSL_ENSURE(m_pView, "no current view?");
-    if(m_pView)
+    OSL_ENSURE(m_pView.is(), "no current view?");
+    if(m_pView.is())
     {
         // keep self alive until done.
         acquire();
@@ -400,14 +403,14 @@
     {
     case RET_LOAD_DOC:
         {
-            SwView* pNewView = lcl_LoadDoc(m_pView, m_pWizard->GetReloadDocument());
+            rtl::Reference< SwView > pNewView = lcl_LoadDoc(m_pView, m_pWizard->GetReloadDocument());
 
             // destroy wizard asynchronously
             Application::PostUserEvent(
                 LINK( this, SwMailMergeWizardExecutor, DestroyWizardHdl ), m_pWizard );
 
             SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
-            if(pNewView)
+            if(pNewView.is())
             {
                 m_pView = pNewView;
                 m_pMMConfig->DocumentReloaded();
@@ -427,11 +430,11 @@
         }
     case RET_TARGET_CREATED:
         {
-            SwView* pTargetView = m_pMMConfig->GetTargetView();
+            rtl::Reference< SwView > pTargetView = m_pMMConfig->GetTargetView();
             uno::Reference< frame::XFrame > xFrame =
                 m_pView->GetViewFrame()->GetFrame().GetFrameInterface();
             xFrame->getContainerWindow()->setVisible(sal_False);
-            OSL_ENSURE(pTargetView, "No target view has been created");
+            OSL_ENSURE(pTargetView.is(), "No target view has been created");
             if(pTargetView)
             {
                 // destroy wizard asynchronously
@@ -458,7 +461,7 @@
             //create a non-modal dialog that allows to return to the wizard
             //the ConfigItem ownership moves to this dialog
             bool bResult = nRet == RET_EDIT_RESULT_DOC && m_pMMConfig->GetTargetView();
-            SwView* pTempView = bResult ? m_pMMConfig->GetTargetView() : m_pMMConfig->GetSourceView();
+            rtl::Reference< SwView > pTempView = bResult ? m_pMMConfig->GetTargetView() : m_pMMConfig->GetSourceView();
             pTempView->SetMailMergeConfigItem(m_pMMConfig, m_pWizard->GetRestartPage(), !bResult);
             SfxViewFrame* pViewFrame = pTempView->GetViewFrame();
             pViewFrame->GetDispatcher()->Execute(
@@ -468,9 +471,9 @@
         }
     case RET_REMOVE_TARGET:
         {
-            SwView* pTargetView = m_pMMConfig->GetTargetView();
-            SwView* pSourceView = m_pMMConfig->GetSourceView();
-            OSL_ENSURE(pTargetView && pSourceView, "source or target view not available" );
+            rtl::Reference< SwView > pTargetView = m_pMMConfig->GetTargetView();
+            rtl::Reference< SwView > pSourceView = m_pMMConfig->GetSourceView();
+            OSL_ENSURE(pTargetView.is() && pSourceView.is(), "source or target view not available" );
             if(pTargetView && pSourceView)
             {
                 m_pView2Close = pTargetView;
@@ -507,7 +510,7 @@
         }
     default: // finish
         {
-            SwView* pSourceView = m_pMMConfig->GetSourceView();
+            rtl::Reference< SwView > pSourceView = m_pMMConfig->GetSourceView();
             if(pSourceView)
             {
                 SwDocShell* pDocShell = pSourceView->GetDocShell();
@@ -606,8 +609,8 @@
                 case FUNIT_PICA:
                 case FUNIT_POINT:
                 {
-                    SwView* pActView = ::GetActiveView();
-                    sal_Bool bWebView = 0 != PTR_CAST(SwWebView, pActView);
+                    rtl::Reference< SwView > pActView = ::GetActiveView();
+                    sal_Bool bWebView = 0 != REF_CAST(SwWebView, pActView);
                     ::SetDfltMetric(eUnit, bWebView);
                 }
                 break;
@@ -618,7 +621,7 @@
 
         case FN_SET_MODOPT_TBLNUMFMT:
             {
-                sal_Bool bWebView = 0 != PTR_CAST(SwWebView, ::GetActiveView() ),
+                sal_Bool bWebView = 0 != REF_CAST(SwWebView, ::GetActiveView() ),
                      bSet;
 
                 if( pArgs && SFX_ITEM_SET == pArgs->GetItemState(
@@ -763,8 +766,8 @@
         const TypeId aSwViewTypeId = TYPE(SwView);
         const TypeId aSwPreviewTypeId = TYPE(SwPagePreview);
         const TypeId aSwSrcViewTypeId = TYPE(SwSrcView);
-        SfxViewShell* pViewShell = SfxViewShell::GetFirst();
-        while(pViewShell)
+        rtl::Reference< SfxViewShell > pViewShell = SfxViewShell::GetFirst();
+        while(pViewShell.is())
         {
             if(pViewShell->GetWindow())
             {
@@ -775,9 +778,9 @@
                     if(bAccessibility)
                     {
                         if(pViewShell->IsA(aSwViewTypeId))
-                            ((SwView*)pViewShell)->ApplyAccessiblityOptions(*pAccessibilityOptions);
+                            ((SwView*)pViewShell.get())->ApplyAccessiblityOptions(*pAccessibilityOptions);
                         else if(pViewShell->IsA(aSwPreviewTypeId))
-                            ((SwPagePreview*)pViewShell)->ApplyAccessiblityOptions(*pAccessibilityOptions);
+                            ((SwPagePreview*)pViewShell.get())->ApplyAccessiblityOptions(*pAccessibilityOptions);
                     }
                     pViewShell->GetWindow()->Invalidate();
                 }
diff --git a/sw/source/ui/app/applab.cxx b/sw/source/ui/app/applab.cxx
index 9c25742..97ab609 100644
--- a/sw/source/ui/app/applab.cxx
+++ b/sw/source/ui/app/applab.cxx
@@ -194,7 +194,13 @@
 
         SfxViewFrame* pViewFrame = SfxViewFrame::DisplayNewDocument( *xDocSh, rReq );
 
-        SwView      *pNewView = (SwView*) pViewFrame->GetViewShell();
+#if OSL_DEBUG_LEVEL > 0
+        rtl::Reference< SwView > pNewView = dynamic_cast<SwView*>(pViewFrame->GetViewShell().get());
+        assert( (  pNewView.is() &&  pViewFrame->GetViewShell().is() ) ||
+                ( !pNewView.is() && !pViewFrame->GetViewShell().is() ));
+#else
+        rtl::Reference< SwView > pNewView = static_cast<SwView*>(pViewFrame->GetViewShell().get());
+#endif
         pNewView->AttrChangedNotify( &pNewView->GetWrtShell() );// So that SelectShell is being called.
 
         // Set document title
diff --git a/sw/source/ui/app/appopt.cxx b/sw/source/ui/app/appopt.cxx
index 4c1c241..d52a96d 100644
--- a/sw/source/ui/app/appopt.cxx
+++ b/sw/source/ui/app/appopt.cxx
@@ -72,6 +72,10 @@
 using namespace ::com::sun::star::uno;
 using namespace ::com::sun::star::lang;
 
+// TODO: move to rtl/ref.hxx
+#define REF_CAST( T, pObj ) \
+    ( pObj.is() && (pObj)->IsA( TYPE(T) ) ? (static_cast<T*>(pObj.get())) : 0 )
+
 SfxItemSet*  SwModule::CreateItemSet( sal_uInt16 nId )
 {
     bool bTextDialog = (nId == SID_SW_EDITOPTIONS);
@@ -80,13 +84,13 @@
         SwViewOption aViewOpt = *GetUsrPref(!bTextDialog);
         SwMasterUsrPref* pPref = bTextDialog ? pUsrPref : pWebUsrPref;
         // no MakeUsrPref, because only options from textdoks can be used here
-        SwView* pAppView = GetView();
-        if(pAppView && pAppView->GetViewFrame() != SfxViewFrame::Current())
-            pAppView = 0;
-        if(pAppView)
+        rtl::Reference< SwView > pAppView = GetView();
+        if(pAppView.is() && pAppView->GetViewFrame() != SfxViewFrame::Current())
+            pAppView.clear();
+        if(pAppView.is())
         {
         // if Text then no WebView and vice versa
-            bool bWebView = 0 != PTR_CAST(SwWebView, pAppView);
+            bool bWebView = 0 != REF_CAST(SwWebView, pAppView);
             if( (bWebView &&  !bTextDialog) ||(!bWebView &&  bTextDialog))
             {
                 aViewOpt = *pAppView->GetWrtShell().GetViewOptions();
@@ -126,7 +130,7 @@
         pRet->Put( SfxBoolItem(FN_PARAM_CRSR_IN_PROTECTED, aViewOpt.IsCursorInProtectedArea()));
     }
 
-    if( pAppView )
+    if( pAppView.is() )
     {
         SwWrtShell& rWrtShell = pAppView->GetWrtShell();
 
@@ -169,26 +173,26 @@
     }
     if(bTextDialog)
         pRet->Put(SwPtrItem(FN_PARAM_STDFONTS, GetStdFontConfig()));
-    if( PTR_CAST( SwPagePreview, SfxViewShell::Current())!=0)
+    if( REF_CAST( SwPagePreview, SfxViewShell::Current())!=0)
     {
         SfxBoolItem aBool(SfxBoolItem(SID_PRINTPREVIEW, sal_True));
         pRet->Put(aBool);
     }
 
     FieldUnit eUnit = pPref->GetHScrollMetric();
-    if(pAppView)
+    if(pAppView.is())
         pAppView->GetHRulerMetric(eUnit);
     pRet->Put(SfxUInt16Item( FN_HSCROLL_METRIC, static_cast< sal_uInt16 >(eUnit)));
 
     eUnit = pPref->GetVScrollMetric();
-    if(pAppView)
+    if(pAppView.is())
         pAppView->GetVRulerMetric(eUnit);
     pRet->Put(SfxUInt16Item( FN_VSCROLL_METRIC, static_cast< sal_uInt16 >(eUnit) ));
     pRet->Put(SfxUInt16Item( SID_ATTR_METRIC, static_cast< sal_uInt16 >(pPref->GetMetric()) ));
     pRet->Put(SfxBoolItem(SID_ATTR_APPLYCHARUNIT, pPref->IsApplyCharUnit()));
     if(bTextDialog)
     {
-        if(pAppView)
+        if(pAppView.is())
         {
             const SvxTabStopItem& rDefTabs =
                     (const SvxTabStopItem&)pAppView->GetWrtShell().
@@ -216,7 +220,7 @@
     pRet->Put(aGridItem);
 
     // Options for PrintTabPage
-    const SwPrintData* pOpt = pAppView ?
+    const SwPrintData* pOpt = pAppView.is() ?
                         &pAppView->GetWrtShell().getIDocumentDeviceAccess()->getPrintData() :
                         0;
 
@@ -240,13 +244,13 @@
 void SwModule::ApplyItemSet( sal_uInt16 nId, const SfxItemSet& rSet )
 {
     bool bTextDialog = nId == SID_SW_EDITOPTIONS;
-    SwView* pAppView = GetView();
-    if(pAppView && pAppView->GetViewFrame() != SfxViewFrame::Current())
+    rtl::Reference< SwView > pAppView = GetView();
+    if(pAppView.is() && pAppView->GetViewFrame() != SfxViewFrame::Current())
         pAppView = 0;
-    if(pAppView)
+    if(pAppView.is())
     {
         // the text dialog mustn't apply data to the web view and vice versa
-        bool bWebView = 0 != PTR_CAST(SwWebView, pAppView);
+        bool bWebView = 0 != REF_CAST(SwWebView, pAppView);
         if(bWebView == bTextDialog)
             pAppView = 0;
     }
@@ -255,7 +259,7 @@
     SwMasterUsrPref* pPref = bTextDialog ? pUsrPref : pWebUsrPref;
 
     const SfxPoolItem* pItem;
-    SfxBindings *pBindings = pAppView ? &pAppView->GetViewFrame()->GetBindings()
+    SfxBindings *pBindings = pAppView.is() ? &pAppView->GetViewFrame()->GetBindings()
                                  : NULL;
 
 
@@ -313,7 +317,7 @@
         const SfxUInt16Item* pMetricItem = (const SfxUInt16Item*)pItem;
         FieldUnit eUnit = (FieldUnit)pMetricItem->GetValue();
         pPref->SetHScrollMetric(eUnit);
-        if(pAppView)
+        if(pAppView.is())
             pAppView->ChangeTabMetric(eUnit);
     }
 
@@ -322,7 +326,7 @@
         const SfxUInt16Item* pMetricItem = (const SfxUInt16Item*)pItem;
         FieldUnit eUnit = (FieldUnit)pMetricItem->GetValue();
         pPref->SetVScrollMetric(eUnit);
-        if(pAppView)
+        if(pAppView.is())
             pAppView->ChangeVRulerMetric(eUnit);
     }
 
@@ -330,7 +334,7 @@
     {
         sal_uInt16 nTabDist = ((const SfxUInt16Item*)pItem)->GetValue();
         pPref->SetDefTab(nTabDist);
-        if(pAppView)
+        if(pAppView.is())
         {
             SvxTabStopItem aDefTabs( 0, 0, SVX_TAB_ADJUST_DEFAULT, RES_PARATR_TABSTOP );
             MakeDefTabs( nTabDist, aDefTabs );
@@ -382,7 +386,7 @@
             const SwAddPrinterItem* pAddPrinterAttr = (const SwAddPrinterItem*)pItem;
             *pOpt = *pAddPrinterAttr;
 
-            if(pAppView)
+            if(pAppView.is())
                 pAppView->GetWrtShell().getIDocumentDeviceAccess()->setPrintData( *pOpt );
         }
 
@@ -395,7 +399,7 @@
             pBindings->Invalidate(FN_SHADOWCURSOR);
     }
 
-    if( pAppView )
+    if( pAppView.is() )
     {
         SwWrtShell &rWrtSh = pAppView->GetWrtShell();
         const bool bAlignFormulas = rWrtSh.GetDoc()->get( IDocumentSettingAccess::MATH_BASELINE_ALIGNMENT );
@@ -481,11 +485,11 @@
                 if ( fnCreatePage )
                     pRet = (*fnCreatePage)( pParent, rSet );
             }
-            SwView* pCurrView = GetView();
-            if(pCurrView)
+            rtl::Reference< SwView > pCurrView = GetView();
+            if(pCurrView.is())
             {
                 // if text then not WebView and vice versa
-                bool bWebView = 0 != PTR_CAST(SwWebView, pCurrView);
+                bool bWebView = 0 != REF_CAST(SwWebView, pCurrView);
                 if( (bWebView &&  RID_SW_TP_HTML_OPTTABLE_PAGE == nId) ||
                     (!bWebView &&  RID_SW_TP_HTML_OPTTABLE_PAGE != nId) )
                 {
@@ -512,8 +516,8 @@
             }
             if (pRet && (nId == RID_SW_TP_OPTSHDWCRSR || nId == RID_SW_TP_HTML_OPTSHDWCRSR))
             {
-                SwView* pCurrView = GetView();
-                if(pCurrView)
+                rtl::Reference< SwView > pCurrView = GetView();
+                if(pCurrView.is())
                 {
                     aSet.Put( SwWrtShellItem( SID_WRT_SHELL, pCurrView->GetWrtShellPtr() ) );
                     pRet->PageCreated(aSet);
diff --git a/sw/source/ui/inc/view.hxx b/sw/source/ui/inc/view.hxx
index 3c85761..a3bbb95a 100644
--- a/sw/source/ui/inc/view.hxx
+++ b/sw/source/ui/inc/view.hxx
@@ -28,6 +28,7 @@
 #include <sfx2/objsh.hxx>
 #include <editeng/svxenum.hxx>
 #include <sfx2/zoomitem.hxx>
+#include <svx/fmshell.hxx>
 #include <svx/svxids.hrc>
 #include <editeng/editstat.hxx>
 #include "swdllapi.h"
@@ -192,8 +193,8 @@
     SwEditWin           *m_pEditWin;
     SwWrtShell          *m_pWrtShell;
 
-    SfxShell            *m_pShell;        // current SubShell at the dispatcher
-    FmFormShell         *m_pFormShell;    // DB-FormShell
+    rtl::Reference< SfxShell >    m_pShell;        // current SubShell at the dispatcher
+    rtl::Reference< FmFormShell > m_pFormShell;    // DB-FormShell
 
     SwView_Impl         *m_pViewImpl;     // Impl-data for UNO + Basic
 
@@ -373,8 +374,8 @@
     void            SetSelectionType(int nSet) { m_nSelectionType = nSet;}
 
     // for SwWebView
-    void            SetShell( SfxShell* pS )            { m_pShell = pS; }
-    void            SetFormShell( FmFormShell* pSh )    { m_pFormShell = pSh; }
+    void            SetShell( rtl::Reference< SfxShell > pS )            { m_pShell = pS; }
+    void            SetFormShell( rtl::Reference< FmFormShell > pSh )    { m_pFormShell = pSh; }
 
     virtual void    SelectShell();
 
@@ -589,11 +590,11 @@
     OUString    GetPageStr(sal_uInt16 nPhyNum, sal_uInt16 nVirtNum, const OUString& rPgStr);
 
     // hand over Shell
-                 SfxShell       *GetCurShell()  { return m_pShell; }
+    rtl::Reference< SfxShell >   GetCurShell()  { return m_pShell; }
                  SwDocShell     *GetDocShell();
     inline const SwDocShell     *GetDocShell() const;
-    inline       FmFormShell    *GetFormShell() { return m_pFormShell; }
-    inline const FmFormShell    *GetFormShell() const { return m_pFormShell; }
+    inline       rtl::Reference< FmFormShell > GetFormShell() { return m_pFormShell; }
+    inline const rtl::Reference< FmFormShell > GetFormShell() const { return m_pFormShell; }
 
     // so that in the SubShells' DTors m_pShell can be reset if applicable
     void ResetSubShell()    { m_pShell = 0; }
@@ -628,7 +629,8 @@
     void ApplyAccessiblityOptions(SvtAccessibilityOptions& rAccessibilityOptions);
 
     SwView(SfxViewFrame* pFrame, SfxViewShell*);
-    ~SwView();
+    virtual ~SwView();
+    virtual void dispose();
 
     void NotifyDBChanged();
 
diff --git a/sw/source/ui/uiview/view.cxx b/sw/source/ui/uiview/view.cxx
index 7e783ba..ecfc2b1 100644
--- a/sw/source/ui/uiview/view.cxx
+++ b/sw/source/ui/uiview/view.cxx
@@ -1031,11 +1031,10 @@
     GetViewFrame()->GetWindow().AddChildEventListener( LINK( this, SwView, WindowChildEventListener ) );
 }
 
-SwView::~SwView()
+SwView::dispose()
 {
     GetViewFrame()->GetWindow().RemoveChildEventListener( LINK( this, SwView, WindowChildEventListener ) );
-    delete m_pPostItMgr;
-    m_pPostItMgr = 0;
+    FREEZ(m_pPostItMgr);
 
     m_bInDtor = sal_True;
     m_pEditWin->Hide(); // damit kein Paint Aerger machen kann!
@@ -1060,22 +1059,28 @@
     m_pViewImpl->Invalidate();
     EndListening(*GetViewFrame());
     EndListening(*GetDocShell());
-    delete m_pScrollFill;
-    delete m_pWrtShell;
+    FREEZ(m_pScrollFill);
+    FREEZ(m_pWrtShell);
     m_pWrtShell = 0;      // Set to 0, so that it is not accessable by the following dtors cannot.
-    m_pShell = 0;
-    delete m_pHScrollbar;
-    delete m_pVScrollbar;
-    delete m_pHRuler;
-    delete m_pVRuler;
-    delete m_pTogglePageBtn;
-    delete m_pPageUpBtn;
-    delete m_pNaviBtn;
-    delete m_pPageDownBtn;
-    delete m_pGlosHdl;
-    delete m_pViewImpl;
-    delete m_pEditWin;
-    delete m_pFormatClipboard;
+    m_pShell.clear();
+    m_pFormShell.clear();
+    FREEZ(m_pHScrollbar);
+    FREEZ(m_pVScrollbar);
+    FREEZ(m_pHRuler);
+    FREEZ(m_pVRuler);
+    FREEZ(m_pTogglePageBtn);
+    FREEZ(m_pPageUpBtn);
+    FREEZ(m_pNaviBtn);
+    FREEZ(m_pPageDownBtn);
+    FREEZ(m_pGlosHdl);
+    FREEZ(m_pViewImpl);
+    FREEZ(m_pEditWin);
+    FREEZ(m_pFormatClipboard);
+}
+
+SwView::~SwView()
+{
+    dispose();
 }
 
 SwDocShell* SwView::GetDocShell()