From 250669f75ad871bdf934cef8eebfc66148183d20 Mon Sep 17 00:00:00 2001
From: James Turner <zakalawe@mac.com>
Date: Tue, 11 Aug 2020 14:06:15 +0100
Subject: [PATCH] Fix circular ownership in FGFX

FGFX isA SGSampleGroup, but owns some SGXmlSounds, which also take an
owning ref to their sample group. Clear out the XMLSounds on unbind(),
to break the circular reference.
---
 src/Sound/fg_fx.cxx | 14 ++++++--------
 1 file changed, 6 insertions(+), 8 deletions(-)

diff --git a/src/Sound/fg_fx.cxx b/src/Sound/fg_fx.cxx
index 62e85e5d3..592bba21b 100644
--- a/src/Sound/fg_fx.cxx
+++ b/src/Sound/fg_fx.cxx
@@ -90,17 +90,17 @@ void FGFX::unbind()
     {
         _smgr->remove(_refname);
     }
+
+    // because SGXmlSound has an owning ref back to us, we need to
+    // clear these here, or we will never get destroyed
+    std::for_each(_sound.begin(), _sound.end(), [](const SGXmlSound* snd) { delete snd; });
+    _sound.clear();
 }
 
 FGFX::~FGFX ()
 {
-    for (unsigned int i = 0; i < _sound.size(); i++ ) {
-        delete _sound[i];
-    }
-    _sound.clear();
 }
 
-
 void
 FGFX::init()
 {
@@ -156,9 +156,7 @@ FGFX::init()
 void
 FGFX::reinit()
 {
-    for ( unsigned int i = 0; i < _sound.size(); i++ ) {
-        delete _sound[i];
-    }
+    std::for_each(_sound.begin(), _sound.end(), [](const SGXmlSound* snd) { delete snd; });
     _sound.clear();
     init();
 }