
J.D. Herron:
I have a suggestion for the shared pointer implementation to overcome a severe limitation it has currently regarding dynamically unloaded libraries. I posted a little while back regarding this problem which is illustrated with the following example from a Microsoft Windows environment. I have a simple factory interface like so:
class Factory { public: virtual shared_ptr<int> GetIntSharedPtr() = 0; virtual int * GetIntRawPtr() = 0; };
... It is indeed a limitation of shared_ptr that it doesn't work when its creator code is unloaded. In this respect it is similar to the following raw pointer code: class X { ~X(); // ... }; class XFactory { public: virtual X * GetRawPtr() = 0; }; in which case ~X resides in the DLL. The advantage of the current shared_ptr code is that both the creation and the destruction of the pointee happen at the same place - inside the DLL. This allows it to support DLLs which do not use the same operator new/delete/malloc/free as the main executable. The general way to solve this problem is as Emil suggests: extend the lifetime of the DLL so that it isn't unloaded while its code is needed. If you just need support for ints/PODs and can guarantee that the EXE and the DLL agree on operator new/delete, you ought to return an auto_ptr<> from the factory. You can assign the auto_ptr to a shared_ptr on the client side and it will be deleted properly. Returning an auto_ptr (or, in the new C++, an unique_ptr) is a way to state to the caller that the pointee can be delete'd from its side - which is what you want. A shared_ptr return implies that the creator retains the right to dispose of the pointee and the exact way to do so is unspecified (it can even retain its own shared_ptr or weak_ptr to it for some reason if the program logic requires). This in turn implies that the code of the creator must remain in memory. :-) -- Peter Dimov http://www.pdplayer.com