且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么 C++ 库和框架从不使用智能指针?

更新时间:2023-11-14 09:08:52

除了许多库是在标准智能指针出现之前编写的,最大的原因可能是缺乏标准的 C++ 应用程序二进制接口 (ABI)).

Apart from the fact that many libraries were written before the advent of standard smart pointers, the biggest reason is probably the lack of a standard C++ Application Binary Interface (ABI).

如果您正在编写一个只有头文件的库,您可以将智能指针和标准容器传递给您的核心内容.它们的源代码在编译时可供您的库使用,因此您只依赖于它们接口的稳定性,而不是它们的实现.

If you’re writing a header-only library, you can pass around smart pointers and standard containers to your heart’s content. Their source is available to your library at compile time, so you rely on the stability of their interfaces alone, not of their implementations.

但由于缺乏标准 ABI,您通常不能安全地跨模块边界传递这些对象.GCC shared_ptr 可能不同于 MSVC shared_ptr,后者也可能不同于 Intel shared_ptr.即使使用相同编译器,也不能保证这些类在版本之间是二进制兼容的.

But because of the lack of standard ABI, you generally cannot pass these objects safely across module boundaries. A GCC shared_ptr is probably different from an MSVC shared_ptr, which too can differ from an Intel shared_ptr. Even with the same compiler, these classes are not guaranteed to be binary compatible between versions.

最重要的是,如果您想发布一个预构建版本的库,您需要一个可依赖的标准 ABI.C 没有,但编译器供应商非常擅长给定平台的 C 库之间的互操作性 - 有事实上的标准.

The bottom line is that if you want to distribute a prebuilt version of your library, you need a standard ABI on which to rely. C doesn’t have one, but compiler vendors are very good about interoperability between C libraries for a given platform—there are de facto standards.

情况对 C++ 来说没有那么好.各个编译器可以处理它们自己的二进制文件之间的互操作,因此您可以选择为每个受支持的编译器分发一个版本,通常是 GCC 和 MSVC.但鉴于此,大多数库只导出 C 接口——这意味着原始指针.

The situation is not as good for C++. Individual compilers can handle interoperation between their own binaries, so you have the option of distributing a version for every supported compiler, often GCC and MSVC. But in light of this, most libraries just export a C interface—and that means raw pointers.

然而,非库代码通常应该更喜欢智能指针而不是原始代码.

Non-library code should, however, generally prefer smart pointers over raw.