shared data between multiple instances of module : thoughts / guidelines?

I’m working on a module that will potentially use several different wav files (read only) and I load them only as needed. Not really on purpose, but as a shortcut to test out an idea, I created the array of wav file contents as a global. It then occurred to me that, since they are read-only and I plan on using multiple instances of the module at once, that it was quite economical to keep them as a shared resource, though I will prob refactor to share via static members instead.

To my question: I want to clean up the wav files in my destructor, but since they are shared… I see 3 options:

  • just nuke 'em and let the other fend for them selves, reload as needed. In this case this wouldn’t be bad, but it would def feel dirty, but thorough…
  • just leave 'em as a memory leak…
  • keep count of the number of instances as a static variable and nuke the shared resources any time the currently destructing instance is the only one.

Any thoughts or guidelines out there?

cheers, Daniel

I’d go for the 3rd solution (counter of instances using the resource and once that reaches zero, then delete the resource).

1 Like

thanks!

Rack 2 offers an optional void destroy() callback that your plugin can define to clean up globals (such as a std::map of samples) when unloaded. This is useful when Rack is used as a VST plugin. The DAW will unload Rack, which unloads all plugins. To use, simply add

void destroy() {
	mySamples.clear();
}

to your plugin.cpp file.

3 Likes

If you look at my ObjectCache object, I’ve been doing this for years. I use shared pointers and weak pointers. Basically the same as your number three, but I let the std library keep count for me. Also, you don’t need to tell it when you go away, just let the shared pointers go out of scope.

4 Likes

I’m gonna give this approach a try. Thanks!

1 Like

Starting from @Squinky’s code I found this document: efficient-plugins.md. I highly recommend it if you haven’t read it. Thanks Squinky!

[quote=“dgbillotte, post:7, topic:14493”] I highly recommend it if you haven’t read it [/quote].

Oh, thanks! Yeah, that’s been a popular document. And it’s nice and short.

I actually have two repos for VCV stuff. The new newer one, Demo, is where most of my documents and demo code lives. Admittedly most of it isn’t as good as the old efficient plugin doc, but I think some are ok.

That repo is over here: GitHub - squinkylabs/Demo: A collection of code and articles of interest to VCV users and developers.