Visual C++ GC 接口如何启用它以及要包含哪个库

Visual C++ GC Interface How to enable it and which library to include

我开始学习 C++ 中的 GC 接口,运行 Visual 2019 C++ 网络上的一些示例可用于以下功能:

上面的每个参考都有一个示例代码,在我的 VC++ 2019 中编译并成功执行

我想知道 VS2019 是否默认启用了 GC - 我的意思是我们不需要启用某些编译器开关或库来添加链接。

此外,如果默认启用了 GC 那么为什么我们没有 'set_pointer_safety' 而只有“get_pointer_safety”?

那么我们如何使用 VC++ 中的 GC 功能,例如 GC 导致内存被取消分配?

Visual C++ 没有实现垃圾 collection,因此 whether/how 启用它或它需要哪些库的问题没有实际意义。

列出的函数的存在并不意味着 GC 存在。这仅意味着 VC++ 实现了 C++11 规定的接口,这些接口将 允许 GC 工作。但是从最新版本 2019 开始提供了 none,而这些功能的 VC++ 实现只是 no-ops,具有“指针安全模型" 返回为 pointer_safety::relaxed,即 none。引用自 VC++ memory header:

// GARBAGE COLLECTION
enum class pointer_safety { relaxed, preferred, strict };

inline void declare_reachable(void*) {}

template <class _Ty>
_Ty* undeclare_reachable(_Ty* _Ptr) {
    return _Ptr;
}

inline void declare_no_pointers(char*, size_t) {}

inline void undeclare_no_pointers(char*, size_t) {}

inline pointer_safety get_pointer_safety() noexcept {
    return pointer_safety::relaxed;
}

来自 Stroustrup 的 GC ABI 常见问题解答:

relaxed: safely-derived and not safely-derived pointers are treated equivalently; like C and C++98 [...]

关于 C++11 GC 的更多信息:

I started learning GC interface in C++

你读过 C++11 标准吗n3337

Visual C++ GC Interface How to enable it and which library to include

正如其他人所解释的,Visual C++ 中没有真正的 GC

写一个简单的garbage collector相当容易。

刚刚阅读 the GC handbook for guidance, and/or the Dragon Book, and/or Lisp In Small Pieces or this Uniprocessor Garbage Collection Techniques 论文。

请注意,您的 GC 的 C++ 垃圾收集标记或复制例程可以通过类似于 SWIG in the spirit of the s11n 库的工具生成

如果您的代码库很小(几十万行 C++ 和几十个 C++ class-es),您甚至可能 生成 GC 支持使用您自己的元程序(或使用 GPP preprocessor or the GNU m4 one or GNU gawk). If you can and are allowed to compile your C++ code with a recent GCC (e.g. GCC 10 in July 2020), consider writing your GCC plugin to generate garbage collection support C++ code. See also [this draft][9] report, and the references inside it. Notice the garbage collector inside GCC.

您可能会对 Boehm's conservative GC library, or by Frama-C, or by the Clang static analyzer 感兴趣。

但是编写最先进的高性能 GC 需要付出很多努力,尤其是当您的 C++ 程序是多线程时。

PS。在 github and gitlab and elsewhere you'll find several open source implementations in C or C++ of garbage collected languages, e.g. this (or GNU guile or Python or GHC or Ocaml). I recommend studying -for inspiration- their C++ or C source code. And GCC has internally its own garbage collector (see also my old unmaintained GCC MELT 项目和我写的几张幻灯片上)。