c++11:它的gc接口是什么,如何实现?

c++11: what is its gc interface, and how to implement?

我在看 Bjarne Stroustrup 的演讲 "The Essence of C++"。

在 44:26 他提到了 "C++11 specifies a GC Interface"。

请问什么是接口,如何实现? 有没有更详细的网上介绍,或者一些示例代码来演示一下?

Stroustrup 在他的 C++ FAQ 中扩展了这个讨论,问题是 GC 的使用是可选的,库供应商可以自由实施或不实施:

Garbage collection (automatic recycling of unreferenced regions of memory) is optional in C++; that is, a garbage collector is not a compulsory part of an implementation. However, C++11 provides a definition of what a GC can do if one is used and an ABI (Application Binary Interface) to help control its actions.

The rules for pointers and lifetimes are expressed in terms of "safely derived pointer" (3.7.4.3); roughly: "pointer to something allocated by new or to a sub-object thereof." to ordinary mortals: [...]

支持此功能的 C++ 标准中的函数(Stroustrup 所指的 "interface")是:

这些函数在 the N2670 proposal 中介绍:

Its purpose is to support both garbage collected implementations and reachability-based leak detectors. This is done by giving undefined behavior to programs that "hide a pointer" by, for example, xor-ing it with another value, and then later turn it back into an ordinary pointer and dereference it. Such programs may currently produce incorrect results with conservative garbage collectors, since an object referenced only by such a "hidden pointer" may be prematurely collected. For the same reason, reachability-based leak detectors may erroneously report that such programs leak memory.

要么您的实现支持 "strict pointer safety"(在这种情况下可以实现 GC),要么它具有 "relaxed pointer safety"(默认情况下),在这种情况下则不能。如果可用,您可以通过查看 std::get_pointer_safety() 的结果来确定。

我不知道任何实际的标准 C++ GC 实现,但至少 标准正在为它的发生做准备

除了我投票赞成的 quantdev 的好答案之外,我想在这里提供更多信息(不适合发表评论)。

这是一个符合 C++11 的程序,它演示了一个实现是否支持 GC 接口:

#include <iostream>
#include <memory>

int
main()
{
#ifdef __STDCPP_STRICT_POINTER_SAFETY__
    std::cout << __STDCPP_STRICT_POINTER_SAFETY__ << '\n';
#endif
    switch (std::get_pointer_safety())
    {
    case std::pointer_safety::relaxed:
        std::cout << "relaxed\n";
        break;
    case std::pointer_safety::preferred:
        std::cout << "preferred\n";
        break;
    case std::pointer_safety::strict:
        std::cout << "strict\n";
        break;
    }
}

输出:

relaxed

意味着该实现有一个简单的实现,它什么都不做。

libc++ 输出:

relaxed

VS-2015 输出:

relaxed

gcc 5.0 输出:

prog.cc: In function 'int main()':
prog.cc:10:13: error: 'get_pointer_safety' is not a member of 'std'
    switch (std::get_pointer_safety())
            ^