# Singleton but reference counted?

**URL:** <https://forum.juce.com/t/singleton-but-reference-counted/55456>\
**Category:** General JUCE discussion\
**Created:** [March 22, 2023, 9:15am UTC](https://forum.juce.com/t/singleton-but-reference-counted/55456 "2023-03-22T09:15:57Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kraku](https://avatars.discourse-cdn.com/v4/letter/k/74df32/32.png) [@Kraku](https://forum.juce.com/u/Kraku)\
**Post date:** [March 22, 2023, 9:15am UTC](https://forum.juce.com/t/singleton-but-reference-counted/55456/1 "2023-03-22T09:15:57Z")

</div>

I want to have a single instance of a GUI class for multiple instances of other classes. I.e. 1 x GUI, 100 x ClassX.

Each ClassX instance should have a pointer to the same instance of the GUI. For this I used JUCE\_DECLARE\_SINGLETON in the GUI.

ClassX constructor calls the GUI::getInstance() to create/get the singleton.  
ClassX destructor calls the GUI::deleteInstance() to get rid of the singleton.

Everything seems to go fine until I delete one of the ClassX instances to create a new one. The singleton’s deleteInstance() simply deletes the GUI, instead of reference counting it. So now all ClassX instances try to access deleted GUI.

Is there some helper macro/method in JUCE which makes it easy to achieve this “reference counted singleton”?

---

<div class="post-metadata">

**Author:** ![anthony-nicholls](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/anthony-nicholls/32/1246_2.png) [@anthony-nicholls](https://forum.juce.com/u/anthony-nicholls)\
**Post date:** [March 22, 2023, 9:22am UTC](https://forum.juce.com/t/singleton-but-reference-counted/55456/2 "2023-03-22T09:22:07Z")

</div>

See the [SharedResourcePointer](https://docs.juce.com/master/classSharedResourcePointer.html) as a potential alternative, I think it does exactly what you want.

---

<div class="post-metadata">

**Author:** ![Kraku](https://avatars.discourse-cdn.com/v4/letter/k/74df32/32.png) [@Kraku](https://forum.juce.com/u/Kraku)\
**Post date:** [March 22, 2023, 9:35am UTC](https://forum.juce.com/t/singleton-but-reference-counted/55456/3 "2023-03-22T09:35:42Z")

</div>

Well, that was a quick and easy fix. Thank you! 🙂  
Works!
