Program crash: GC destroys an object unexpectedly

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Sep 21 20:29:01 UTC 2021


On Tue, Sep 21, 2021 at 07:42:48PM +0000, jfondren via Digitalmars-d-learn wrote:
> On Monday, 13 September 2021 at 17:18:30 UTC, eugene wrote:
> > I do not understand at all why GC considers those sg0 and sg1 as
> > unreferenced.
> > And why old gdc (without -Os) and old ldc do not.
> 
> Conclusion:
> 
> There's nothing special about sg0 and sg1, except that they're part of
> Stopper. The Stopper in main() is collected before the end of main()
> because it's not used later in the function and because there are
> apparently no other references to it that the GC can find (because the
> only reference is hidden inside the Linux epoll API).

Quick and dirty workaround: keep references to those objects in static
variables to prevent GC collection:

	auto myFunc(...) {
		static MyType* dontCollect = null;

		MyType* obj = new MyObject(...);
		dontCollect = obj;
		scope(exit) dontCollect = null; // may collect after function exits

		... // function body goes here
	}


T

-- 
Verbing weirds language. -- Calvin (& Hobbes)


More information about the Digitalmars-d-learn mailing list