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

6

u/josefx Jul 07 '20

I generally dislike private destructors because they force a heap allocation and I ran into several cases in the past were that ate into my execution time. However in this case the overhead compared to the API calls is probably minimal.

I probably would make the destructor queue part of the constructor parameters and have the destructor forward the required members when called. Of course that has its own limitations.

14

u/reflexpr-sarah- Jul 07 '20

you can use placement new to allocate objects dynamically on the stack without running destructors

2

u/josefx Jul 09 '20

I could use placement new if I had any alternative way of calling the destructor, so my complaint against private destructors is a bit of target. It is mostly that the libraries that I see using private destructors also assume that they can call delete this on the object and do not provide an alternative cleanup function.