Is it OK to use boost::shared ptr in DLL interface?

前端 未结 5 539
臣服心动
臣服心动 2021-01-04 19:21

Is it valid to develop a DLL in C++ that returns boost shared pointers and uses them as parameters?

So, is it ok to export functions like this?

1.) b         


        
5条回答
  •  囚心锁ツ
    2021-01-04 19:45

    According to Scott Meyers in Effective C++ (3rd Edition), shared_ptrs are safe across dll boundaries. The shared_ptr object keeps a pointer to the destructor from the dll that created it.

    In his book in Item 18 he states, "An especially nice feature of tr1::shared_ptr is that it automatically uses its per-pointer deleter to eliminate another potential client error, the "cross-DLL problem." This problem crops up when an object is created using new in one dynamically linked library (DLL) but is deleted in a different DLL. On many platforms, such cross-DLL new/delete pairs lead to runtime errors. tr1::shared_ptr avoid the problem, because its default deleter uses delete from the same DLL where the tr1::shared_ptr is created."

    Tim Lesher has an interesting gotcha to watch for, though, that he mentions here. You need to make sure that the DLL that created the shared_ptr isn't unloaded before the shared_ptr finally goes out of scope. I would say that in most cases this isn't something you have to watch for, but if you're creating dlls that will be loosely coupled then I would recommend against using a shared_ptr.

    Another potential downside is making sure both sides are created with compatible versions of the boost library. Boost's shared_ptr has been stable for a long while. At least since 1.34 it's been tr1 compatible.

提交回复
热议问题