291 points · by adamnemecek · 10y ago · 83 comments
Quite a few developers believe that if you don't have these features you aren't writing "real C++" but it's common practice in quite a few industries where size/performance is critical.
My experience with exceptions is different, though, and I see them used quite a bit. It depends a lot on the age of the code base and the group working on it. Old code is less likely to use them, and developers with a heavy C background, or a lot of pre-C++98 experience are less like to use them. Except for maybe some tiny embedded systems (like microcontrollers), the overhead of exceptions isn't that bad any more.
And then C++ exceptions don't come with a stack trace that makes quick and dirty exceptions based code so convenient in Java or C#.
I was never a principled opponent of exceptions, but I find myself removing them from more and more code the more thoroughly I think about all the possible error states of code that should really be robust.
Generally I haven't found any error handling solution where exceptions provided superior semantics. The lack of checking means that you can catch more bugs with enum error codes + switch and Wall.
I have, but it's almost never the extremely limited built-in RTTI.
> Except for maybe some tiny embedded systems (like microcontrollers), the overhead of exceptions isn't that bad any more.
Big caveat here: Unthrown / rare exceptions aren't that bad.
I ran into a bug with the windows 8 touch APIs, where the pointer ID for a given finger would become invalid just before we recieved the "pointer up" notification if you pawed at the screen in just the right way. This manifested as an exception being thrown when querying the pointer position - which, of course, wasn't caught, meaning pawing at the screen just right crashed the program.
Catching the exception stopped it from crashing, at least. But the framerate would tank if you pawed at the screen, from exception handling overhead alone.
I've come to frown on exceptions in C++, for production gamedev. Everything else is using error codes anyways, why add a second error handling style into the mix? Your callbacks may be invoked from third party C, which you can't safely throw across, or C++ built with exceptions disabled, which you also can't safely throw across. Heck, just building with exceptions enabled can be difficult - I could not link against some of the C++ PS4 libraries without matching many of their build settings - including having exception handling disabled.
...I resorted to alternative options for handling failed unit tests.
There are a large number of programmers who use C++ "because it's fast," and they've heard RTTI and exceptions (and virtual function calls, ...) are slow, so they avoid those features.
But the common implementations for RTTI and exceptions have improved. They're much faster than they used to be. The performance problem isn't that they're slow, but that their performance is unpredictable. Not terribly unpredictable, but unpredictable enough to rule them out in real time code.
But for most everyone else, they're plenty fast. Or, put another way, if RTTI and exceptions make your project noticeably slower, you're doing too many dynamic_casts and/or throwing too many exceptions.
At this point the question should be "does this lead to a good design?" and not "does my gut think it's fast enough?"
The difference being that they created their own version.
Well, I use exceptions in exactly one situation: my request handlers on the server are all one-shot, transactional, and throwing anywhere unwinds to the top of the stack, aborts the transaction, and results in an error message being returned to the caller.
For that specific use case, I find exceptions cleaner than any other approach I've tried. Otherwise, I avoid them as well.
Regarding exceptions, in my experience it depends a lot of the cultural background of the developers: Unix developers tend to use them, Windows developers don't.
https://stackoverflow.com/questions/23383102/dynamic-cast-tr...
I've seen it first hand crap itself on Mac OS X. The gist of it is that if you have a plugin architecture, you can't pass an object allocated in one plugin to another and have the latter do a dynamic_cast. For the same reason exceptions thrown in a plugin can't be caught in another unless the type is defined in the host binary. I.e. suppose the main application has:
class HostException {
virtual ~HostException() {}
};
class FooInterface {
virtual void doBar()=0;
};
Then inside plugin A you do try {
foo->doBar();
} catch (HostException& ex) {
// stuff
}
where foo was allocated in plugin B. Then, // in plugin B
class FooImpl : public FooInterface {
virtual void doBar() override;
};
class MyException : public HostException {
virtual ~MyException() {}
};
void FooImpl::doBar() {
throw HostException(); // should be just fine
throw MyException(); // here be dragons
}
For that reason in places where we call foreign code that we know could throw we just do a blanket catch(...) and bail out on any exception. Similarly we don't rely on dynamic casts at all anywhere, we use our own type system.The OOP features of C++ are fine for small toy programs but ironically they break when you try to use them for actual large ones that would benefit the most from them. Stick to virtual functions, static and reinterpret casts and nothing else.
"However, for existing code, the introduction of exceptions has implications on all dependent code. If exceptions can be propagated beyond a new project, it also becomes problematic to integrate the new project into existing exception-free code. Because most existing C++ code at Google is not prepared to deal with exceptions, it is comparatively difficult to adopt new code that generates exceptions."
Would the use exceptions if they could do it again?
[1] http://llvm.org/docs/CodingStandards.html#do-not-use-rtti-or...
I dislike exceptions too, but in a difference-of-opinion way where I can be like “OK, that otherwise legible and reasonable code uses exceptions, unlike mine” and it doesn’t make me grimace like I involuntarily do for RTTI… I’d love to be mistaken tho, anyone with an inspiring counterexample, do share.
Personally I like to turn everything on, but I also understand there are use-cases where it isn't possible.
My first C++ compiler was Turbo C++ 1.0 for MS-DOS, so I also used this kind of bare metal programming back in the day.
What I don't like is "C with classes" which throws away all the safety mechanisms that C++ offers over C, to the point the code could be compiled with a C compiler.
However the advices presented in the "Practical Guide to Bare Metal C++" look quite good.
I for one am perfectly happy with “C with destructors and templates”. The usual criticism of “C with classes” is levelled at a specific kind of code that’s neither particularly good C++ nor particularly good C. But not all “C with classes” is necessarily that way.
No-one should need to listen to a bunch of fanatics. Different problems are have different constraints. Some problems are easier to solve using a different formalism than some other. People try to sound like Herb Sutter or Stroustrup when peddling their "best practice" advice after looking at a few lines of code and deciding it's not to their liking. Sutter and Stroustrup usually have a grasp of the higher level context, while random best practice commisars in the web, seldom dont.
Since C++ contains so many footguns the charitable explanation is that they grasp to the only way of coding they can hold in their head.
Damn the establishment! C++ offers a refreshing multiplicty of styles of implementation. ML style for data transforms, lispish dynamic lists for parsers, vanilla object style for some problem domains, relational style with structs of indices for others. Note: solutions of these styles can be wrapped in a nice cplusplushy interface but if one starts to solve the problem from the point of view of designing the class hierarchy rather than looking at the data and transforms required often leads to a technically inferior dessign (by which I mean - my designs became much better after I understood to focus on the latter and not the former). One needs to be strict, yes, but the strictness needs to be on a closer-core-cs-concepts level and not on the class design level.
Just wrote a parser in lisp style C++ and loved it (and yes, there were enough constraints to limit C++ as the only language).
And if it is, and if it's exactly what you need, and C is still not good enough, maybe there's a use-case for either a new language, call is --C++, or some kind of "C++ without the bad stuff" accepted standard to drive the entire eco-system forward with well-defined features, boundaries, libraries, tools, all that good stuff?
As for your proposal - why? I can already disable exceptions and RTTI with compiler switches. And is it really a sane idea to spin off a new language if you don't like some library?
I'm sure we all know what happens when your ISR quietly does a new while some other part of your code is holding one of the locks deep in malloc.
But far more important is avoiding priority inversions when a low priority thread is holding a lock in a library somewhere, they result in high priority threads missing real-time deadlines - the sort of heisenbugs that are pretty impossible to find .... and are best to avoid by design.
Yeah, what happens is that such code does not pass code review :)
In 99.99% of cases an ISR should only set some flag, that is then checked by code, running in user mode (or whatever it is called for your platform). Then the real work is done in user mode. The remaining 0.01% of cases does not involve using dynamic memory either.
Definitely no exceptions in ISRs. What would an exception really even mean in an ISR context? The "call" is done by the hardware, so there's no stack to unwind. Uncaught exception would practically mean system crash.
Stack usage should be low, because ISR itself might get interrupted by a higher priority IRQ.
ISR (interrupt service routine) needs to return as fast as possible, usually in a few microseconds.
On x86, no FPU or SIMD in ISR either, unless you save and restore the registers. You need to cover all SIMD extensions, current and the future ones. If you use SSE but don't save AVX/AVX-512 registers, expect very weird bug reports. Better to simply avoid.
my point is that there are hidden mutexes in libraries that people often don't know about - his example of replacing new() with malloc() doesn't solve the problem, instead you need to be able to code your C++ without new, or at least the real-time bits of it (and that includes using stuff like strings and their libraries that do new() behind your back, or even printf which can run foul of the stdio hidden mutexes)
It's not just ISRs, priority inversion is a real problem that results in some of the hardest bugs to find (I once had to chase one that happened only once a month, resulting in satellite systems losing their provisioning)
Honestly, these "people" seem like mythical creatures to me; I've certainly never met one. If you're qualified to write an ISR in C++, you're qualified to understand which parts of C++ are valid to use in an ISR and which aren't.
This is a non-problem that does not appear in practice, even though it could in theory.
I agree with him that removing the entire standard library is needed. Of course you then need to copy an implementation of printf from somewhere, and likely set it up to only work in your debug builds. Then you quickly figure out that the standard library has a lot of things you didn't even realize you depended on. Math functions typically pop up next, you'll likely end up using a vendor library (by which I mean ARM's), but if you are doing a bunch of math heavy work, and even more so if your chip has some limited FP capabilities (assuming it has an FPU at all), you may also find the need to re-implement some functions based on your performance needs.
Embedded is fun. :)
All that said, I would kill for access to proper lambdas.
This makes me feel so old. Back when I started, C on a micro-controller was a rare treat and most things were done in some obscure chip-specific assembler.
I had a play with an Arduino knockoff a few weeks ago, kids these days don't know how good they've got it!
Most of us just get to use the toys already in the package and aren't allowed to bring new ones to the party.
More seriously, the problems (exceptions and rtti) that you are mentioning are actually explained in this tutorial. One can disable them and still enjoy a great part of C++. Rust might be better on some other features though.
What?? 120KB? I have to try that out right away.
Edit: That turned out to be completely wrong. Simple program without throw: 71'218 bytes. With throw (one additional line that throws a plain integer): 71'814 bytes. GCC 4.8.1 on Windows. Would have been surprised if that was true.
Edit2: Okay, my bad, I should have linked statically. The statement sounded so absolute, but of course it is conditioned on the bare metal environment which is the subject of this article. Thanks for pointing out where I went wrong.
g++ -Os -static -s on `int main() { }' 17.408 bytes
g++ -Os -static -s on `int main() { throw 42; }' 139.776 bytesHere's a comment of mine from a previous discussion: https://news.ycombinator.com/item?id=11706840
Building the no exceptions version with -fno-exceptions doesn't change the size of the exception-free version either.
(g++ 4.8.5 with -Os)
In order to not get that, you'll likely have to rebuild the entire runtime library with EH turned off.