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.
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.
It's also true that with more experience, we've figured out that cleanup code is special. When I throw an exception during normal processing, I want to abandon what I'm doing. But if I discover that one step of a destructor cannot be completed, I do not want to abandon the rest of the cleanup. If I throw an exception in a destructor, I can't come back later to finish any remaining steps.
And, as I asked earlier, if I throw an exception because I can't close a file, what do I expect the exception handler to do? I guess it could try closing the file again, but I'm not going to hold my breath on that working. Perhaps the file is on a network share and the network's gone down. Perhaps closing the file will involve writing some cached data to disk, but the disk is full. In my experience, in this case your only real options are "ignore it, either because there's nothing you can do or because you're already dealing with an exception and you've simply discovered another symptom of the original problem" or "kill the program because there is no hope." You can log the fact that a step failed, but remember that it's possible for logging to fail, if the disk is full.
In my experience the exact opposite is true. Error handling or "cleanup" code is in no way special. Errors are not exceptional and there is nothing we can say in general about what error handling code will or will not need to do.
Error handling code needs to be able to use the entire language and reuse all the regular code that is used elsewhere. A language should not have two modes, an error mode and a normal mode with completely different non-local semantics.
>And, as I asked earlier, if I throw an exception because I can't close a file, what do I expect the exception handler to do?
That depends entirely on the context of the program you're writing. It might want to do things like writing a record to a database that marks the file as invalid/corrupt. It may need to notify some other system about the failed action. It might want to roll back a transaction or initiate a compensating transaction. It may want to abort some session and schedule it to restart at a later time.
There is simply nothing we can know in general about what a caller of an action that failed to complete cleanly may want to do as a result of that failure.
Using exceptions for error states that may require a complex response is just not a good idea and in C++ it's an even worse idea.
[Edit] But to be clear, my initial thought wasn't about exception handling but rather about ubiquitous use of RAII for all sorts of stuff that needs to get done at the end of a scope. Much of that has nothing to do with errors at all. Maybe if you think of these situations it will become clearer why I think that arbitrary limitations of code that runs in a destructor is problematic. C++ has no finally block. Destructors is all we have.
Classic example is logging an error on failure. This means calling a logging function in the catch block, and then letting the exception propagate. But what if the call to the logging function fails? In Java, coded naively you'd simply drop the original exception. Usually that's not what you want.
You can examine the issue with error codes, it's not any better.
I agree with you on that. It turns out that, say, having a lock guard automatically release a lock when it falls out of scope can cause a ton of trouble when it falls out of scope in a place the programmer overlooked.
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.
In the case of Unreal we used it to extend the RTTI system to to more things than just isA(). Stuff like member properties(editor hints in window), serialization(network & disk) and stuff you'd use C# attributes for.
However when I look to such examples, I am quite happy to spend most of my time on JVM/CLR lands.
It is not the meta-programming as such, rather the decltype, trailing return types and SFINAE tricks that put me off.
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.
You just need to declspec(dllexport) the classes, with the caveat that thanks to the lack of standard ABI you need the same compiler on both sides.
Then again, most other platforms never were too C++ friendly and rather lean on C.
BeOS, Symbian, Genode and Windows are probably the only OSes that give C++ some love.
"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...
"On their face, the benefits of using exceptions outweigh the costs, especially in new projects. 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.
"Given that Google's existing code is not exception-tolerant, the costs of using exceptions are somewhat greater than the costs in a new project. The conversion process would be slow and error-prone. We don't believe that the available alternatives to exceptions, such as error codes and assertions, introduce a significant burden.
"Our advice against using exceptions is not predicated on philosophical or moral grounds, but practical ones. ... Things would probably be different if we had to do it all over again from scratch."
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).
That might be a bit bad example, because IO pin control is usually compiled to just one or at most a few machine instructions. IO pin control for those is often a macro or intrinsic, not really a library.
Sometimes there's no runtime, other than what you implement. That's true bare metal.
Besides not all processors offer MMIO.
Yes well um no, that only happens in a select few embedded bare metal projects, and usually only the ones with fairly beefy processors or large code bases running on them. Once you contemplate in putting a library layer for your project you might as well put down a full rtos or linux, taking us out the focus of this discussion which is bare metal C++ programming.
>> Besides not all processors offer MMIO...
I don't understand what point your trying to make? The vast majority of embedded processors these days offer memory mapped IO, at least so in the ARM set of processors. And if not all processors offer MMIO, so what, what are you trying to say?
I see, they always write everything from scratch.
> And if not all processors offer MMIO, so what
Then you need to wrap the Assembly instructions out* / in* into C functions or sprinkle all the code with inline assembly since libraries aren't used.
Embedded developers, yup pretty much... :| Most projects just copy and pastes the OEM's sample code or previous projects driver code and work from there.
>> Then you need to wrap the Assembly instructions out* / in* into C functions or sprinkle all the code with inline assembly since libraries aren't used.
I have never seen that being done in the last 10 years except for the startup sections on processors setting up the ISR / clocking / co-processors etc.
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?