在 C++ 库接口中安全地使用容器 [英] Safely use containers in C++ library interface

查看:36
本文介绍了在 C++ 库接口中安全地使用容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在设计 C++ 库时,我认为在公共接口中包含像 std::vector 这样的标准库容器是不好的做法(参见例如 在 dll 导出函数中使用 std::vector 的影响).

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 using std::vector in a dll exported function).

如果我想公开一个接受或返回对象列表的函数怎么办?我可以使用一个简单的数组,但随后我必须添加一个 count 参数,这使得界面更加繁琐且不那么安全.例如,如果我想使用 map 也无济于事.我猜像 Qt 这样的库定义了自己的容器,可以安全地导出,但我不想将 Qt 添加为依赖项,也不想推出自己的容器.

What if I want to expose a function that takes or returns a list of objects? I could use a simple array, but then I would have to add a count parameter, which makes the interface more cumbersome and less safe. Also it wouldn't help much if I wanted to use a map, for example. I guess libraries like Qt define their own containers which are safe to export, but I'd rather not add Qt as a dependency, and I don't want to roll my own containers.

在库接口中处理容器的最佳实践是什么?是否可能有一个可以用作胶水"的小型容器实现(最好只有一两个文件,我可以放入,并具有许可许可)?或者有没有办法使 std::vector 等跨 .DLL/.so 边界和使用不同的编译器安全?

What's the best practice to deal with containers in the library interface? Is there maybe a tiny container implementation (preferably just one or two files I can drop in, with a permissive license) that I can use as "glue"? Or is there even a way to make std::vector etc. safe across .DLL/.so boundaries and with different compilers?

推荐答案

实际上,这不仅适用于 STL 容器,而且适用于几乎所有 C++ 类型(特别是所有其他标准库类型).

Actually this is not only true for STL containers but applies to pretty much any C++ type (in particular also all other standard library types).

由于 ABI 未标准化,您可能会遇到各种麻烦.通常,您必须为每个受支持的编译器版本提供单独的二进制文件才能使其工作.获得真正可移植的 DLL 的唯一方法是坚持使用普通的 C 接口.这通常会导致类似于 COM 的结果,因为您必须确保所有分配和匹配的解除分配发生在相同的模块,并且没有向用户公开实际对象布局的详细信息.

Since the ABI is not standardized you can run into all kinds of trouble. Usually you have to provide separate binaries for each supported compiler version to make it work. The only way to get a truly portable DLL is to stick with a plain C interface. This usually leads to something like COM, since you have to ensure that all allocations and matching deallocations happen in the same module and that no details of the actual object layout are exposed to the user.

这篇关于在 C++ 库接口中安全地使用容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆