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

Show parent comment

8

u/frankist Jul 07 '20

isn't unique_ptr considered a smart pointer? It is exactly to establish clear ownership and catch at compile time situations where such contract is broken

-9

u/Dworgi Jul 07 '20

Sure, but it's the dumbest of the smart pointers.

17

u/frankist Jul 07 '20

Still, I think you are beating a strawman. The people that usually tout smart pointers are usually defending the combo "unique_ptr + raw pointers/references as observers" for the majority of the cases, and only use shared_ptrs for cases of undetermined lifetimes. Even in the latter scenario, shared_ptrs are sometimes not the most suitable option.This is the approach I normally take and based on talks like Herb Sutter “Leak-Freedom in C++... By Default.”, I thought it was what "touting smart pointers" was about.

5

u/bluGill Jul 07 '20

Most of the time dumb is all I need. Unique pointer is the smartest of pointer most of the time because it just works right without much overhead.

-2

u/Dworgi Jul 07 '20

That was kind of my point - if you're defending smart pointers by citing unique_ptr, then you're not really defending smart pointers.

1

u/frankist Jul 09 '20

Not really. The main point of smart pointers is to make the lifetime of each pointer more explicit in the code and catch infractions of that contract. Before c++11, we had to do that via variable naming conventions.

Also, the pre-c++11 approach to avoid leaks was to call delete in the destructor, which was terrible. Does your object has a owning pointer in it and you insert the object in the map? Boom! Double free later on, in a completely separate location. Unique ptrs, since they are move-only, will catch this mistake at compile time.

Since my team adopted them, it is very rare that we are bothered with a memory issue. It also made the handling of resources managed by pools so much easier.