Garbage Collection in C++11

12,598

Minimal GC support (n2670) only means functions like std::declare_reachable are included, and define what is the meaning of a "safely-derived pointer", so making certain operations like XOR-ing pointer values becomes undefined behavior and the GC don't need to worry about it. See also Bjarne Stroustrup's C++11 FAQ on the GC ABI, and n2585: Minimal Support for Garbage Collection and Reachability-Based Leak Detection.

The proposal allows a GC to be implemented within C++11's framework. But the proposal itself does not mean the implementation needs to support GC. Some library e.g. libc++ simply implement the library functions as no-op.

I'm pretty sure, at this point, the memory in your case is just leaked away. But notice that the destructor is indeed not required to run when GC happens. Assuming "§3.8 Object lifetime" also supplies to GC-ed pointers, we have (§3.8/4):

... For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; however, if there is no explicit call to the destructor or if a delete-expression (5.3.5) is not used to release the storage, the destructor shall not be implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior.

So it is also possible the memory is already freed without the destructor called. In fact, earlier GC proposals such as n2310: Transparent Programmer-Directed Garbage Collection for C++ explicitly states that (n2310 §7)

When an object is recycled by the garbage collector, its destructor is not invoked (Of course, explicit deletion always invokes destructors).

Share:
12,598

Related videos on Youtube

Adam Reed
Author by

Adam Reed

Updated on June 08, 2022

Comments

  • Adam Reed
    Adam Reed almost 2 years

    I have been looking through and playing with different features of C++11, specifically in Visual Studio 2010.

    One of the things mentioned is minimal garbage collection:

    According to this blog post, VC10 supports this feature.

    My tests show that the destructor is not called on objects that are lost, so I am not sure as to whether their memory location has been freed or if they are leaking.

    I have no intention of depending on it, by any means, but couldn't find a straight, definitive answer on its behavior.

  • Eponymous
    Eponymous about 9 years
    As I understand it, 3.8/4 is a section talking about "the program", not needing to call the destructor. In other words, we don't need to say foo->~MyClass(); delete foo;. In the GC case it would be reasonable to assume that GC running was like using the delete expression - in which case the GC is responsible for calling the destructor.