171

Banned C++ features in Chromium

Nothing particularly notable here. A lot of it seems to be 'We have something in-house designed for our use cases, use that instead of the standard lib equivalent'.

The rest looks very reasonable, like avoiding locale-hell.

Some of it is likely options that sand rough edges off of the standard lib, which is reasonable.

12 hours agoNight_Thastus

> We have something in-house designed for our use cases, use that instead of the standard lib equivalent

Yea, you encounter this a lot at companies with very old codebases. Don't use "chrono" because we have our own date/time types that were made before chrono even existed. Don't use standard library containers because we have our own containers that date back to before the STL was even stable.

I wonder how many of these (or the Google style guide rules) would make sense for a project starting today from a blank .cpp file. Probably not many of them.

11 hours agoryandrake

Don't use standard library containers because we have our own containers that date back to before the STL was even stable.

Flashback to last job. Wrote their own containers. Opaque.

You ask for an item from it, you get back a void pointer. It's a pointer to the item. You ask for the previous, or the next, and you give back that void pointer (because it then goes through the data to find that one again, to know from where you want the next or previous) and get a different void pointer. No random access. You had to start with the special function which would give you the first item and go from there.

They screwed up the end, or the beginning, depending on what you were doing, so you wouldn't get back a null pointer if there was no next or previous. You had to separately check for that.

It was called an iterator, but it wasn't an iterator; an iterator is something for iterating over containers, but it didn't have actual iterators either.

When I opened it up, inside there was an actual container. Templated, so you could choose the real inside container. The default was a QList (as in Qt 4.7.4). The million line codebase contained no other uses; it was always just the default. They took a QList, and wrapped it inside a machine that only dealt in void pointers and stripped away almost all functionality, safety and ability to use std::algorithm

I suspect but cannot prove that the person who did this was a heavy C programmer in the 1980s. I do not know but suspect that this person first encountered variable data type containers that did this sort of thing (a search for "generic linked list in C" gives some ideas, for example) and when they had to move on to C++, learned just enough C++ to recreate what they were used to. And then made it the fundamental container class in millions of lines of code.

10 minutes agoEliRivers

> I wonder how many of these (or the Google style guide rules) would make sense for a project starting today from a blank .cpp file. Probably not many of them.

The STL makes you pay for ABI stability no matter if you want it or not. For some use cases this doesn't matter, and there are some "proven" parts of the STL that need a lot of justification for substitution, yada yada std::vector and std::string.

But it's not uncommon to see unordered_map substituted with, say, sparsehash or robin_map, and in C++ libraries creating interfaces that allow for API-compatible alternatives to use of the STL is considered polite, if not necessarily ubiquitous.

8 hours agoLexiMax

I'd argue that the optimum was in long run to migrate to the standard version, that everyone (e.g. new employees) know. Replacing the usually particular (or even weird) way implemented own flavour.

I know, I know, long run does not exists in today's investor dominated scenarios. Code modernization is a fairytale. So far I seen no exception in my limited set of experiences (but with various codebases going back to the early 90's with patchy upgrades here and there, looking like and old coat fixed many many times with diverse size of patches of various materials and colour).

2 hours agomihaaly

[flagged]

10 hours agomtklein

Look, I even share your language preference but this is still unnecessary.

9 hours agoacdha

Are there really any good reasons to start a brand new project in c++ though? No one who can write modern c++ has any trouble with rust in my experience, and all the other common options are even quicker to pick up. Creating bindings isn't hard anymore if your niche library doesn't have any yet. Syntactic preference I guess, but neither c++ or rust are generally considered elegant or aesthetic choices.

8 hours agogalangalalgol

Because "brand new" doesn't mean devoid of context. Within your domain, there will still be common libraries, interfaces, and tools.

C++ is very flexible, with a lot of very mature tooling and incredibly broad platform support. If you're writing some web server to run on the hardware of your choosing, then sure, that doesn't matter. But if you're writing something deeply integrated with platform/OS interfaces, or graphics, or needs to support some less common platforms, then C++ is often your only practical option for combining expressiveness and performance.

7 hours agocpgxiii

This is the sort of info I was trolling for, but what are those platforms and os? Targets llvm doesn't handle yeah c++ makes sense, or c. A sibling mentions xcode, which makes sense. Graphics seems questionable, vulkan support is fine. Windows support has seemed finetoo, the same gui has worked as what we wrote for Linux.

5 hours agogalangalalgol

Unreal, Godot, CryEngine, DirectX, PlayStation, Switch, XBox, CUDA, SYSCL, LLVM, GCC, V8,...

2 hours agopjmlp

Dependencies. There are billions of lines of C++ out there that have been optimized and production hardened over decades that you might want to reuse. Rust lang interoperability with anything but C sucks in practice.

5 hours agojupp0r

Yes, there are plenty of domains where Rust has zero ecosystem.

Not to mention that Rust advocates keep forgetting their compiler is partially written in C++ (LLVM/GCC).

2 hours agopjmlp

Maybe, maybe not. But either way it's just plain rude to charge into a C++ thread to drop a comment saying how the language sucks and you should use (insert other language) instead.

6 hours agobigstrat2003

Rust becomes a significant burden if you need a GUI or hardware-accelerated graphics.

8 hours agoBearOso

C++ isn't much better for GUI.

3 hours agojenadine

C++ was the GUI king during the 1990's, and none of the Rust toolkits is half as good as the surviving frameworks, like C++ Builder, Qt, wxWidgets, heck even MFC has better tooling.

2 hours agopjmlp

I assume most of them are just grabbing qt

3 hours agojohnny22

In addition to other reasons given: If you have a team of C++ developers, let them use the language they know best.

3 hours agojenadine

Yes. If you're targeting Apple platforms and want to allow clients to use your product in Xcode (the common case) or even need Swift/ObjC interop yourself, using rust or anything not explicitly supported by Apple and Xcode is just too fiddly.

7 hours agokstenerud

Why not pick swift in this situation over c++?

5 hours agogalangalalgol
[deleted]
6 hours ago

(Shrug) If I want Rust, I'll feed my C++ to an LLM and tell it to port it to Rust. Since we've been assured that Rust magically fixes everything that's wrong, bad, or unsafe about C++, this seems like a sound approach.

8 hours agoCamperBob2

We probably aren't that far off actually. Even taking asm with no symbols back into rust works well. You have truth, just have the agent repeat until the asm matches. Doesn't work on giant codebases, but on a few functions it absolutely does. And while the llm may get the algorithm wrong, the type system does seem to help it generate useful code in rust for a starting place v

5 hours agogalangalalgol

Yeah, but then just let the agent generate proper C++ code, contrary to an human it doesn't forget about best practices, or how ownership is supposed to be handled.

2 hours agopjmlp

You missed the other take, with AI assisted coding, you can stay in C++, as it will take care everything is coded with enough care.

Or why bother with Rust, when the LLM gets to generate C++ code with best practices.

While I like Rust, I think AI as the next abstraction step in programming has kind of taken its relevance away, when computer assisted programming is part of the workflow.

2 hours agopjmlp

Strange. I wouldn’t trust the output of a coding agent and I would want stronger review of its output. If it passes a strict compiler that gives me more confidence than if it passed a lax one.

But sure, if you trust it to have written C++ to a higher standard than the experts, then go for it.

2 hours agotestdelacc1

Somewhat notable is that `char8_t` is banned with very reasonable motivation that applies to most codebases:

> Use char and unprefixed character literals. Non-UTF-8 encodings are rare enough in Chromium that the value of distinguishing them at the type level is low, and char8_t* is not interconvertible with char* (what ~all Chromium, STL, and platform-specific APIs use), so using u8 prefixes would obligate us to insert casts everywhere. If you want to declare at a type level that a block of data is string-like and not an arbitrary binary blob, prefer std::string[_view] over char*.

10 hours agovitaut

`char8_t` is probably one of the more baffling blunders of the standards committee.

10 hours agoChrisSD

there is no guarantee `char` is 8 bits, nor that it represents text, or even a particular encoding.

If your codebase has those guarantees, go ahead and use it.

9 hours agojjmarr

> there is no guarantee `char` is 8 bits, nor that it represents text, or even a particular encoding.

True, but sizeof(char) is defined to be 1. In section 7.6.2.5:

"The result of sizeof applied to any of the narrow character types is 1"

In fact, char and associated types are the only types in the standard where the size is not implementation-defined.

So the only way that a C++ implementation can conform to the standard and have a char type that is not 8 bits is if the size of a byte is not 8 bits. There are historical systems that meet that constraint but no modern systems that I am aware of.

[1] https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/n49...

3 hours agohackyhacky
[deleted]
16 minutes ago

char8_t also isn't guaranteed to be 8-bits, because sizeof(char) == 1 and sizeof(char8_t) >= 1. On a platform where char is 16 bits, char8_t will be 16 bits as well

The cpp standard explicitly says that it has the same size, typed, signedness and alignment as unsigned char, but its a distinct type. So its pretty useless, and badly named

9 hours ago20k

wtf

3 hours agojjmarr
[deleted]
8 hours ago

That's where the standard should come in and say something like "starting with C++26 char is always 1 byte and signed. std::string is always UTF-8" Done, fixed unicode in C++.

But instead we get this mess. I guess it's because there's too much Microsoft in the standard and they are the only ones not having UTF-8 everywhere in Windows yet.

an hour agojhasse

std::string is not UTF-8 and can't be made UTF-8. It's encoding agnostic, its API is in terms of bytes not codepoints.

11 minutes agojstimpfle

There's no guarantee char8_t is 8 bits either, it's only guaranteed to be at least 8 bits.

7 hours agoMaxatar

> There's no guarantee char8_t is 8 bits either, it's only guaranteed to be at least 8 bits.

Have you read the standard? It says: "The result of sizeof applied to any of the narrow character types is 1." Here, "narrow character types" means char and char8_t. So technically they aren't guaranteed to be 8 bits, but they are guaranteed to be one byte.

2 hours agohackyhacky

What platforms have char8_t as more than 8 bits?

3 hours agoCyberDildonics

Well platforms with CHAR_BIT != 8. In c and c++ char and there for byte is atleast 8 bytes not 8 bytes. POSIX does force CHAR_BIT == 8. I think only place is in embeded and that to some DSPs or ASICs like device. So in practice most code will break on those platforms and they are very rare. But they are still technically supported by c and c++ std. Similarly how c still suported non 2's complement arch till 2023.

40 minutes agomarcthe12

How many non-8-bit-char platforms are there with char8_t support, and how many do we expect in the future?

9 hours agodataflow

Mostly DSPs

9 hours agoRobotToaster

Is there a single esoteric DSP in active use that supports C++20? This is the umpteenth time I've seen DSP's brought up in casual conversations about C/C++ standards, so I did a little digging:

Texas Instruments' compiler seems to be celebrating C++14 support: https://www.ti.com/tool/C6000-CGT

CrossCore Embedded Studio apparently supports C++11 if you pass a switch in requesting it, though this FAQ answer suggests the underlying standard library is still C++03: https://ez.analog.com/dsp/software-and-development-tools/cce...

Everything I've found CodeWarrior related suggests that it is C++03-only: https://community.nxp.com/pwmxy87654/attachments/pwmxy87654/...

Aside from that, from what I can tell, those esoteric architectures are being phased out in lieu of running DSP workloads on Cortex-M, which is just ARM.

I'd love it if someone who was more familiar with DSP workloads would chime in, but it really does seem that trying to be the language for all possible and potential architectures might not be the right play for C++ in 202x.

Besides, it's not like those old standards or compilers are going anywhere.

4 hours agoLexiMax

Non-8-bit-char DSPs would have char8_t support? Definitely not something I expected, links would be cool.

7 hours agodataflow

Why not? except it is same as `unsigned char` and can be larger than 8 bit

ISO/IEC 9899:2024 section 7.30

> char8_t which is an unsigned integer type used for 8-bit characters and is the same type as unsigned char;

3 hours agoj16sdiz

char on linux arm is unsigned, makes for fun surprises when you only ever dealt with x86 and assumed char to be signed everywhere.

an hour agoAsmod4n

Not an Googler, but my, probably way too much romanticized, understanding of Google was that they never ask you about specific tech because for everything there's an in-house version.

The problem is that too many people drank too much koolaid and trying to parrot everything to a letter without understanding the bigger picture.

The best example would be Kubernetes. Employed by many orgs that have 20 devs and 50 services.

7 hours agozeroq

> for everything there's an in-house version.

Reasonable summary. There's some massive NIH syndrome going on.

Another piece is that a lot of stuff that makes sense in the open source world does not make sense in the context of the giant google3 monorepo with however many billions of lines of code all in one pile.

an hour agodmoy

<regex> [banned]

A good decision. I tried to use it once and realized that it can't even work with UTF-8 properly. It's a mystery for me how such flawed design was standardized at all.

4 hours agoPanzerschrek

Seeing the comments here talking about ancient codebases got me wistful for when Chromium was new and everything seemed possible.

That triggered a flash of feeling extremely old realizing we broke ground on this codebase 20 years ago this year!

9 hours agobengoodger

Exceptions are banned, but an exception is made for Windows.

12 hours agoddtaylor

People that keep bringing this up always miss the rationable that Google code was written initially in a C style that isn't exception safe.

Key takeaway => "Things would probably be different if we had to do it all over again from scratch."

"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. Because we'd like to use our open-source projects at Google and it's difficult to do so if those projects use exceptions, we need to advise against exceptions in Google open-source projects as well. Things would probably be different if we had to do it all over again from scratch."

2 hours agopjmlp

I'm quite happy to NOT have exceptions. I think they're a mistake as a language feature. What we need is first -class support for returning errors and propagating them, like what zig does. The next best thing are those RETURN macros that Google uses.

an hour ago8n4vidtmkvmk

grep'd "exception" and "Windows", tl;dr only Windows reference is for `[[no_unique_address]]`. Therefore I am probably missing a joke :)

12 hours agorefulgentis

Where does it list the preferred alternatives to banned features?

For example:

> The <filesystem> header, which does not have sufficient support for testing, and suffers from inherent security vulnerabilities.

11 hours agoTempest1981

For most of the banned library features, the preferred alternative is listed right there in the notes. <filesystem> is one of the exceptions.

11 hours agocomex

base/files

11 hours agojeffbee

Gonna venture a guess and say probably https://www.chromium.org/developers, as that's where all the information for folks who actually need to know that kind of thing lives.

11 hours agoTheRealPomax
[deleted]
11 hours ago

Good call on those u8"..." literals.

Source code should all be UTF-8 natively, letting you directly write UTF-8 text between quotes.

Exactly their rationale.

These literals are a solution in search of a problem ... which is real but has a much better solution.

9 hours agokazinator

Is there a way to make this formal, like in the code, making the compiler complain when you try to use these features?

11 hours agoamelius

I'm not a c++ user but i'm pretty sure you should be able to pull-off a macro to do that ; in c you could alias the lib for something that breaks + alert ; I don't know how I would integrate such additional compiler checks in rust for other kinds of rules however - it's interesting to think about

10 hours ago6r17

It’s a bit different, but WebKit uses Clangs static analysis.

10 hours agoTingPing

It is relatively easy to check these things with static analyzers, if nothing else.

10 hours agoloeg

Kythe can be used for that

9 hours agomkoubaa

You almost never see a list of banned Java features (or even banned C# features). On the other hand any serious C++ development team is going to have a list of banned features. Java eliminated the features that you would want to ban.

10 hours agolateforwork

This seems factually incorrect and ignorant of history. Java has tons of things which shouldn't be used. Serialization (use Jackson now, not the built-in stuff), date/time (there's an entirely different namespace so you don't accidentally use garbage classes), etc.

C# similarly has old warts that are discouraged now. .NET Framework is a great example (completely different from modern c#, which used to be called "dotnet core"). WPF and MAUI are also examples. Or when "dynamic" was used as a type escape hatch before the type system advanced to not need it. ASP being incompatible with ASP.NET, the list goes on.

They're just languages, there's no reason to pretend they're perfect.

10 hours agonilamo

C# can be used in both .NET Framework and modern .NET (ex-core). In fact, it is possible for a C# project to target both .NET Framework and .NET with the exact same code, or to target to .NET Standard, where the same .DLL file can be loaded by both. Since the old Framework is in maintenance mode, some modern language features will not work there, but you can still be productive with the old framework.

Dynamic is largely unnecessary, and it was unnecessary even when it was introduced.

ASP and ASP.NET are completely unrelated. ASP was designed to allow dynamic webpages to be written in VBScript (like CGI). This is not something you want to do in modern languages.

39 minutes agoKwpolska

> C# similarly has old warts that are discouraged now. .NET Framework is a great example (completely different from modern c#, which used to be called "dotnet core"). WPF and MAUI are also examples. Or when "dynamic" was used as a type escape hatch before the type system advanced to not need it. ASP being incompatible with ASP.NET, the list goes on.

Almost all of this is incorrect or comparing apples to oranges.

.net framework and .net core are runtime and standard library impl, not languages. C# is a language that can target either runtime or both. Framework is still supported today, and you can still use most modern C# language features in a project targeting it. WPF and Maui are both still supported and widely used. ASP predates .net - c# was never a supported language in it. ASP.net core has largely replaced ASP.net, but it's again a library and framework, not a language feature.

Dynamic in c# and the dlr are definitely not widely used because it's both difficult to use safely and doesn't fit well with the dominant paradigm of the language. If you're looking for STD lib warts binaryserializer would have been an excellent example.

9 hours agotwisteriffic

Dynamic is still nice when you’re dealing with unknown data imo. More hygienic to read than dictionary access through string keys for example.

I use it when deserializing unknown message types.

42 minutes agotubs

Those are libraries not language features.

10 hours agolateforwork

So is nearly all of this list.

9 hours agoplorkyeran

There are clearly demarcated language features sections and library sections. That definitely makes sense for C++, it is a poorly designed language and you definitely have to know what features to avoid.

9 hours agolateforwork

> C++, it is a poorly designed language

Unlike C# that has both delegates and lambdas, for example. Also finalizers and IDisposable.

2 hours agodrysine

dynamic is a language feature

9 hours agobathtub365
[deleted]
9 hours ago

In C#, you would normally implement rules like this with a custom Roslyn Analyzer or with https://github.com/dotnet/roslyn/blob/main/src/RoslynAnalyze.... It’s fair to say C# projects tend to have smaller denylists than mature C++ projects, but banned APIs definitely exist in mature C# projects.

8 hours agooldmanhorton

I think Java has plenty of features that end up implicitly banned at least. e.g. you will really never see a `java.util.Vector` in any modern code base. No one `implements Serializable` anymore in practice. `Objects.equals()` and `Objects.hashCode()` get you through 99% of equals/hash code implementations. The list goes on.

I guess the difference is it's rarely "dangerous" or "hard to reason about" using the old features unlike what I see in the C++ list. Java replaces things with better things and momentum shifts behind them kind of naturally because the better things are objectively better.

9 hours agojameslars

I have, many companies have style guides enforced via Sonar and similar tools, what you don't see is everyone putting them on the Internet.

2 hours agopjmlp

> You almost never see a list of banned Java features ...

The instanceof[0] operator is typically banned from use in application code and often frowned upon in library implementations.

0 - https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.htm...

9 hours agoAdieuToLogic

I've never heard of that being banned. It hasn't been banned anywhere i've written Java.

9 hours agotwic

Never seen this being banned. Whats the reason?

an hour agoMrBuddyCasino

As a Java programmer I can only think of one thing:

Reflection - unless you really need to do something fancy almost certainly a very bad idea in normal application code.

Other than that it’s either just limiting yourself to a specific JVM version or telling people not to use old syntax/patterns that were replaced with better options long ago.

9 hours agoMBCook

I would imagine most codebases, even in modern languages, tend to have a list of banned features. Typically you use a linter to catch these.

9 hours agomadeofpalk

I'd curious about the banned Rust features. Surely, Rust has at lot fewer foot guns, but it isn't that there aren't any.

9 hours agoweinzierl

Heard of `#![forbid(unsafe_code)]` ?

9 hours agojtrueb

It's that effectively enforcement of features that are banned?

2 hours agobulbar

#![deny(clippy::unwrap_used)]

3 hours agojenadine

I doubt unsafe would be blatantly banned. I was more thinking of things like glob imports.

6 hours agoweinzierl
[deleted]
9 hours ago

This list is longer than the features in all of C I feel like at first glance. Wow that is overwhelming.

9 hours agobfrog

The banned list proves that context matters more than having the newest tools. These features work well for small apps but they cause problems in a project this size.

12 hours agodfajgljsldkjag

IIRC a big part of Google’s coding guidelines is also about making it easy for people not heavily invested in a specific language to contribute safely. So not necessarily a project size but rather an organizational concern.

They’d rather see it done the same way it would’ve been in any other similar language than with a language specific feature.

There are also portability concerns in mind given that projects like Chromium have to be easily portable across a vast amount of platforms (this shows with things like long long which is also on the list).

10 hours agotrinix912

Go is an extremely cynical language in this regard.

9 hours agojonstewart

Some of it is historical reasons or portability more than anything else. Chrome is an old C++ project and evolved many of its own versions of functionality before standardization; and there's benefit to staying on its own implementations rather than switching.

10 hours agoloeg

Agreed. I also prefer conformity over sporadic use of new features going against an already set of standards in a codebase. it's overall less cognitive load on whoever is reading it imho.

6 hours agodiabllicseagull

Modules are banned - they should have just copied D modules.

11 hours agoWalterBright

Since Chromium stopped allowing manifest-v2 extensions, i.e. significantly crippled what extensions can do and made it impossible to use some key extensions like uBlock Origin, I've decided to avoid it.

Anyway, about these C++ conventions - to each software house its own I guess. I don't think banning exceptions altogether is appropriate; and I don't see the great benefit of using abseil (but feel free to convince me it's really that good.)

10 hours agoeinpoklum

If nothing else Abseil gives you state-of-the-art hashmaps that run circles around the STL ones, which are slow pretty much by definition. The spec precludes the modern ways of implementing them.

9 hours agojsheard

Rust is too complicated!!11 Ooops wrong thread.

8 hours agonixosbestos

C++ itself should be forever banned

11 hours agogrougnax

Ok. You can stop using anything written in C++.

2 hours agoj16sdiz

How would you implement a C++ ban in Chromium?

3 hours agoExpurple

It's remarkable to me how many codebases ban exceptions and yet, somehow, people still insist they're good.

12 hours agojesse__

> 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.

They are clearly not against them per se. It simply wasn't practical for them to include it into their codebase.

And I think a lot of the cons of exceptions are handled in languages like F#, etc. If f calls g which calls h, and h throws an exception, the compiler will require you to deal with it somehow in g (either handle or explicitly propagate).

12 hours agoBeetleB

My issue with exceptions is also practical. If they didn't introduce significant stability issues, I'd have no problem. As it stands, it's impossible to write robust software that makes use of C++ exceptions.

> the compiler will require you to deal with it somehow in g

I agree, this is the sensible solution.

12 hours agojesse__

What stability issues?

11 hours agoyunnpp

Unchecked exceptions will eventually lead into programs crashing because some developer forgot to catch specific type of exception somewhere.

7 hours agorauli_

And developers never forget to check error codes.

2 hours agodrysine

In low-level systems software, which is a primary use case for C++, exceptions can introduce nasty edge cases that are difficult to detect and reason about. The benefits are too small to justify the costs to reliability, robustness, and maintainability.

Exceptions in high-level languages avoid many of these issues by virtue of being much further away from the metal. It is a mis-feature for a systems language. C++ was originally used for a lot of high-level application code where exceptions might make sense that you would never use C++ for today.

11 hours agojandrewrogers

> In low-level systems software, which is a primary use case for C++

I don't this this is true. There is A LOT of C++ for GUI applications, video games, all kind of utilities, scientific computing and others. In fact, I find that the transition to "modern" alternatives from native GUI toolkits in C/C++ has led to a regression in UI performance in general. Desktop programs performed better 20 years ago when everything was written in Win32, Qt, GTK and others and people did not rely on bloated Web toolkits for desktop development. Even today you can really feel how much more snappy and robust "old school" programs are relative to Electron and whatnot.

11 hours agodrnick1

To clarify, you think that low-level systems software is only a secondary use case for C++? The part you quoted does not make claims about whether there are other primary use cases, just that low-level systems software is one of them, so it's not clear why it being useful elsewhere is a rebuttal of that.

10 hours agosaghm

There are only so many OS kernels to be written. Nothing else is really low-level these days.

4 hours agoTylerE

> In low-level systems software, which is a primary use case for C++

I can assure you: Most C++ SW is not written for low-level.

> exceptions can introduce nasty edge cases that are difficult to detect and reason about.

That's true, except for languages that ensure you can't simply forget that something deep down the stack can throw an exception.

BTW, I'm not saying C++'s exceptions are in any way good. My point is that exceptions are bad in C++, and not necessarily bad in general.

11 hours agoBeetleB

The model of communicating errors with exceptions is really nice. The implementation in C++ ABI's is not done as well as it could be and that results in large sad path perf loss.

11 hours agobeached_whale

> That's true, except for languages that ensure you can't simply forget that something deep down the stack can throw an exception.

Sometimes it is not safe to unwind the stack. The language is not relevant. Not everything that touches your address space is your code or your process.

Exception handlers must have logic and infrastructure to detect these unsafe conditions and then rewrite the control flow to avoid the unsafety. This both adds overhead to the non-exceptional happy path and makes the code flow significantly uglier.

The underlying cause still exists when you don't use exceptions but the code for reasoning about it is highly localized and usually has no overhead because you already have the necessary context to deal with it cleanly.

11 hours agojandrewrogers

> Sometimes it is not safe to unwind the stack.

This where garbage collected languages shine.

7 hours agole-mark

If you forget to handle a C++ exception you get a clean crash. If you forget to handle a C error return you get undefined behavior and probably an exploit.

Exceptions are more robust, not less.

11 hours agokllrnohj

Yeap. forgetting to propagate or handle an error provided in a return value is very very easy. If you fail to handle an exception, you halt.

11 hours agonomel

For what it's worth, C++17 added [[nodiscard]] to address this issue.

6 hours agovasilvv

You should compare exceptions to Result-style tagged unions in a language with exhaustiveness checks, like Rust. Not to return codes in C, lmao.

Everyone (except Go devs) knows that those are the worst. Exceptions are better, but still less reliable than Result.

https://home.expurple.me/posts/rust-solves-the-issues-with-e...

3 hours agoExpurple

> like Rust

Where people use things like anyhow.[0]

[0] https://docs.rs/anyhow/latest/anyhow/

2 hours agodrysine

Anyhow erases the type of the error, but still indicates the possibility of some error and forces you to handle it. Functionality-wise, it's very similar to `throws Exception` in Java. Read my post

21 minutes agoExpurple

C++ exceptions are fast for happy path and ABI locked for sad path. They could be much faster than they are currently. Khalil Estell did a few talks/bunch of work on the topic and saw great improvements. https://youtu.be/LorcxyJ9zr4

11 hours agobeached_whale

Oops, I meant they are ABI locked so sad path cannot be fixed.

6 hours agobeached_whale

> "In low-level systems software, which is a primary use case for C++, exceptions can introduce nasty edge cases that are difficult to detect and reason about. The benefits are too small to justify the costs to reliability, robustness, and maintainability."

Interestingly, Microsoft C / C++ compiler does support structured exception handling (SEH). It's used even in NT kernel and drivers. I'm not saying it's the same thing as C++ exceptions, since it's designed primarily for handling hardware faults and is simplified, but still shares some core principles (guarded region, stack unwinding, etc). So a limited version of exception handling can work fine even in a thing like an OS kernel.

11 hours agosenfiaj

FWIW, I think it is possible to make exception-like error handling work. A lot of systems code has infrastructure that looks like an exception handling framework if you squint.

There are two main limitations. Currently, the compiler has no idea what can be safely unwound. You could likely annotate objects to provide this information. Second, there is currently no way to tell the compiler what to do with an object in the call stack may not be unwound safely.

A lot of error handling code in C++ systems code essentially provides this but C++ exceptions can't use any of this information so it is applied manually.

10 hours agojandrewrogers

Exceptions are actually a form of code compression. Past some break even point they are a net benefit, even in embedded codebases. They're "bad" because the C++ implementation is garbage but it turns out it's possible to hack it into a much better shape:

https://youtu.be/LorcxyJ9zr4

11 hours agomatheusmoreira

There is no such thing as the 'C++ implementation' of exceptions. Each vendor can do it differently.

11 hours agosecondcoming

Is this correct? I don't know F# but I thought it had unchecked exceptions. How does it handle using C# libs that throw unchecked exceptions?

11 hours agojayd16

The “pros” list is exceptionally weak. This was clearly written by someone who doesn’t like exceptions. Can’t blame them.

12 hours agoheyitsdaad

Most codebases that ban exceptions do it because they parrot Google.

Google’s reasons for banning exceptions are historical, not technical. Sadly, this decision got enshrined in Google C++ Style Guide. The guide is otherwise pretty decent and is used by a lot of projects, but this particular part is IMO a disservice to the larger C++ ecosystem.

11 hours agoazov

I agree. I've worked on large C++ code bases that use exceptions, and they've never caused us any real problems.

11 hours agoalextingle

I think reasonable people can disagree about whether C++ exceptions are "good" or not.

There are things you can't do easily in C++ without using exceptions, like handling errors that happen in a constructor and handling when `new` cannot alloc memory. Plus, a lot of the standard library relies on exceptions. And of course there's the stylistic argument of clearly separating error-handling from the happy-path logic.

I won't argue that it's popular to ban them, though. And often for good reasons.

11 hours agoryandrake

For exception-less C++, you'd declare an operator new() that doesn't throw exceptions and just returns NULL on allocation failure along with a simple constructor and a followup explicitly-called init() method that does the real work which might fail and returns an error value on failure.

9 hours agocanucker2016

They're good for exceptional situations where foundamental, core assumptions are broken for some reason.

In such scenario there's no error recovery, software is expected to shutdown and raise loud error.

12 hours agotester756

If you're planning on shutting down, what's the fundamental difference between throwing an exception, vs simply complaining loudly and calling exit() ..?

12 hours agojesse__

Sometimes it’s useful to handle the exception somewhere near its origin so you can close related resources, lockfiles, etc. without needing a VB6 style “On Error GoTo X” global error handler that has to account for all different contexts under which the exceptional situation might have occurred.

12 hours agotrinix912

Your process can crash or be killed at any moment anyway. Depending on in-band cleanup is not reliable.

11 hours agoPhilipRoman

Sure, but there are many cases where you don't have to halt because you can cleanup and carry on.

11 hours agonomel

> a VB6 style “On Error GoTo X” global error handler that has to account for all different contexts under which the exceptional situation might have occurred

... That seems like a pretty accurate description of how exception handling mechanisms are implemented under the hood. :)

11 hours agomatheusmoreira

The code that's throwing an exception typically does not know that the exception catcher will shut anything down.

And - very often, you would _not_ shut down. Examples:

* Failure/error in an individual operation or action does not invalidate all others in the set of stuff to be done.

* Failure/error regarding the interaction with one user does not mean the interaction with other users also has to fail.

* Some things can be retried after failing, and may succeed later: I/O; things involving resource use, etc.

* Some actions have more than one way to perform them, with the calling code not being able to know apriori whether all of them are appropriate. So, it tries one of them, if it fails tries another etc.

10 hours agoeinpoklum

Yet, if you can only explain an exception using the word ‘exception’ you’re not making any head way.

I like the idea of an exception as a way to blow out of the current context in order for something else to catch it and handle in a generic manner. I don’t like the idea of an exception to hide errors or for conditional logic because you have to know what is handling it all. Much easier to handle it there and then, or use a type safe equivalent (like a maybe or either monad) or just blow that shit up as soon as you can’t recover from the unexpected.

11 hours agoljm

> They're good for exceptional situations where foundamental, core assumptions are broken for some reason.

No, that's what assertions or contracts are for.

Most exceptions are supposed to be handled. The alternative to exceptions in C++ are error codes and `std::expected::. They are used for errors that are expected to happen (even if they may be exceptional). You just shouldn't use exceptions for control flow. (I'm looking at you, Python :)

10 hours agospacechild1

I use asserts for this purpose.

12 hours agodijit

Looking at this ban list, they've removed everything from C++ that makes it fun. Come on people, who doesn't love a little std::function?!?

On banning exceptions:"Things would probably be different if we had to do it all over again from scratch."

https://google.github.io/styleguide/cppguide.html#Exceptions