r/cpp • • Jul 06 '20

C++ is brilliant

I'm working on a Vulkan renderer, and needed to delay destruction of render scenes since the graphics pipeline has render buffers in flight, so destruction has to happen N frames after the user destroys a class. With C++, I can use private destructors to force users to add the scene to a managed destructor queue (aka garbage collect queue). Normally language purists will scorn a language which allows such shenanigans, however in real world production code, its features like this which allows developers to create modern software. So with a couple of lines of code, I solved my delayed destructor issue. Thank you C++ committee for creating a usable language.

318 Upvotes

65 comments sorted by

View all comments

127

u/MutantSheepdog Jul 07 '20

Yep, that would work.

Easier approach for others to implement would just be to have those buffers/textures loaded/stored/referenced with shared_ptrs, and that way destruction would happen after no entity is using it and rendering has finished.

Slightly less efficient, but easier to implement.

23

u/MoreOfAnOvalJerk Jul 07 '20

Downside to this is that the dtors can be called in surprising situations. If they have performance overhead, it might cause unpredictable spikes.

It sounds like he already has some abstraction managing the lifetime of the buffers so it might make the most sense and possibly be the most performant if it also manages when to destroy and deallocate them.

16

u/Dworgi Jul 07 '20

Exactly this. People always tout smart pointers as some sort of panacea, but ignore that the performance characteristics can be unacceptable - you might release your final reference to an object somewhere performance critical, then have a cascade of destructors all triggering as a result of that destructor.

Smart pointers are a hack around clear ownership. It allows you to avoid the least important memory bugs - use after free - but does nothing to solve the actual problem of ownership and lifetimes.

13

u/Ameisen vemips, avr, rendering, systems Jul 07 '20

Of course, you could have the final dereference put the object into a queue and destroy it on a garbage collection thread.

6

u/evaned Jul 07 '20

... destroy it on a garbage collection thread.

Or at a fixed location on the main thread, of course.

Another benefit this has is that it solves something that is occasionally a problem with most smart pointers on deeply-nested structures, which is a stack overflow when deconstructing the structure.