Safely use containers in C++ library interface

前端 未结 4 988
予麋鹿
予麋鹿 2021-02-02 00:28

When designing a C++ library, I read it is bad practice to include standard library containers like std::vector in the public interface (see e.g. Implications of us

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-02 00:53

    TL;DR There is no issue if you distribute either the source code or compiled binaries for the various supported sets of (ABI + Standard Library implementation).

    In general, the latter is seen as cumbersome (with reasons), thus the guideline.


    I trust hand-waving guidelines about as far as I can throw them... and I encourage you to do the same.

    This guidelines originates from an issue with ABI compatibility: the ABI is a complex set of specifications that defines the exact interface of a compiled library. It is includes notably:

    • the memory layout of structures
    • the name mangling of functions
    • the calling conventions of functions
    • the handling of exception, runtime type information, ...
    • ...

    For more details, check for example the Itanium ABI. Contrary to C which has a very simple ABI, C++ has a much more complicated surface area... and therefore many different ABIs were created for it.

    On top of ABI compatibility, there is also an issue with Standard Library Implementation. Most compilers come with their own implementation of the Standard Library, and these implementations are incompatible with each others (they do not, for example, represent a std::vector the same way, even though all implement the same interface and guarantees).

    As a result, a compiled binary (executable or library) may only be mixed and matched with another compiled binary if both were compiled against the same ABI and with compatible versions of a Standard Library implementation.

    Cheers: no issue if you distribute source code and let the client compile.

提交回复
热议问题