Using boost::shared_ptr in a library's public interface

前端 未结 10 2353
再見小時候
再見小時候 2021-02-14 05:31

We have a C++ library that we provide to several different clients. Recently we made the switch from using raw pointers in the public interface to using boost::sharedptr instead

10条回答
  •  走了就别回头了
    2021-02-14 06:07

    First of all, if you distribute your library as source code rather than as a compiled library, you can disregard this answer. There are also some windows specific problems that may not be relevant for other platforms.

    I personally think you should avoid having too much funky c++ in the public interface of your library since it can cause a lot of problems at the client.

    I'm not sure how applicable this is to your particular example, but I've personally run into problems where symbols from the stl library I used conflicted with the ones in the third party library when I upgraded to a new version. This meant we got crashes in strange places and I had to do lots of tricks to avoid the problem. In the end I stayed with the old version of the library because of this.

    Another problem you can run into is that different c++ compilers can mangle the same symbols differently which means you potentially need to provide a separate library for every compiler you want to support even if they use the same Boost version. Check out the book "Imperfect C++" for a discussion on this.

    In the current world of different C++ compilers and environments I think the sad truth is that you should avoid having anything but C in your interface and make sure you link your library dynamically (to avoid conflicts when linking your customers links your library, windows runtime library can be a real pain here). You can still use boost and as much fancy c++ on the inside of your library as you want since all your symbols will be isolated from your customers environment in the dll.

    If you really want to have smart pointers and other nice C++ functionality in the interface of your library, build a convenience layer which you distribute the source code for. This will make sure it's always compiled in the customers environment. This interface then calls your exposed C functions in clever ways. I don't think it's a good idea to use boost in that layer either since it will force your customers to adopt it even if they don't want, however it's easy to replace it or find another solution since that layer is distributed as source code.

    Another nice feature is that it's generally easier to call C functions in a dll than c++ functions with strange name mangling if you want to expose your library to other languages than C/C++.

    This approach definitely makes your life more complicated in many ways, but it's a way of making it less likely that people avoid your library because it just wasn't possible to link successfully with their own code.

提交回复
热议问题