4 ms·
I have a couple of gripes with these guidelines, not because I love writing unsafe programs, but because this way of writing C++ conflicts with the reality of h
by Asooka 4y ago
I have a couple of gripes with these guidelines, not because I love writing unsafe programs, but because this way of writing C++ conflicts with the reality of how C++ is implemented.
1. shared_ptr is very slow. It makes it safe to share data, but at the expense of many tiny allocations for each object type. C++'s memory manager isn't geared towards that kind of abuse, this is something that can really only be performant in a garbage-collected language where allocation is an atomic pointer increment and deallocation happens "later". Pushing people towards using this abstraction is wrong most of the time, it is often much better to use arena-style allocations for most cases in C++. I've seen libraries written in modern C++ where malloc and free account for 80% of the runtime. I don't see a way to fix this without radically altering the memory manager.
2. The impact on code compiled in debug mode is often unacceptable. I expect programs compiled with minimal to no optimisations to be slower, but layering all these abstractions usually produces a lot of runtime junk that gets in the way. For example, std::for_each can often be optimised to a regular for loop, which can then be vectorised, but in debug mode it is compiled to a function call which in turn calls the passed in lambda for each element and operator++ on the iterator. The difference in speed between the two is several orders of magnitude and makes this abstraction unacceptable for hot loops. This is a more minor gripe that can probably be solved by marking some functions as "function-like macros" similar in intent to LISP's macros, so the compiler knows they can be always inlined and optimised. GCC's -Og flag also helps a lot here. Still, the world isn't just GCC and the standard should probably bequeath more library functions with special status, like how memcpy &al can be always optimised to inlined machine code instead of a function call.
You'll notice both of those concern speed. If the loss of performance from said abstractions is not a deal-breaker for you, then you probably shouldn't be writing C++. D, C#, go, Java, maybe even JavaScript, Python or Lua would be a better choice for your project. The reason to use C++ for a new project is because you want to build really complex programs made up of operations that closely match the semantics of the machine on which they run, for the purpose of going very fast. Or you're stuck using C++ because you have to interface with C++.
- tomjakubowski 4y agoshared_ptr is compatible with arena allocation - look up the "aliasing constructor".