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

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

问题描述

在设计C ++库时,我读到在公共接口中包含诸如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天全站免登陆