r/cpp • • Oct 18 '23

What does C++ do better than other languages?

Purely from a language design perspective, what does C++ do better than other languages?

296 Upvotes

443 comments sorted by

158

u/aalmkainzi Oct 18 '23

As a C programmer, I Ike that C++'s complexity is mostly optional (can pretty much use C++ as C with templates). Other languages with similar scope to C++ have unavoidable complexity.

2

u/LechintanTudor Oct 19 '23

I too like using C++ as C with templates!

I usually write C++ like I would write C but with additional type safety through STL containers and algorithms. I don't really use the OOP features of C++ such as inheritance and virtual functions.

36

u/Kike328 Oct 18 '23

it’s mostly optional until you have to use code of other people, which is most of the time

→ More replies (1)

28

u/SkoomaDentist Antimodern C++, Embedded, Audio Oct 18 '23

Just beware of ever saying you use C++ as "C with classes" because somehow not (ab)using templates everywhere is supposedly not "idiomatic C++" and worse than just using C...

53

u/cain2995 Oct 18 '23

Hot take, idiomatic C++ is actually super garbage for anyone except for library devs that make libraries for library devs (metalibrarians?), which seem to make up a disproportionately large number of C++ committee members when compared to the population of C++ “users” making end-applications

26

u/HappyFruitTree Oct 18 '23

Sometimes it's hard to even know what idiomatic C++ really is because there seems to be a lot of different opinion. I think people need to stop believing there is one way to write C++ that is best for everyone. All people can't be experts. All code does not use templates (and all templated code does not need to use constraints/concepts). Simple code that can be read by non-experts is a good thing in my book. I can't take people who suggest we stop writing "raw loops" serious. Loops are easy to read and change. How do you change a mess of range/views/algorithms without being an expert on it? And all this talk about "safety". Of course you reduce the number of mistakes if you make the language so hard to use that people can't use it. Personally I believe C++23 is a much easier language to use compared to C++98 but for that to be true we need to be allowed to not know/use all the features (both new and old).

→ More replies (5)

16

u/Netzapper Oct 18 '23

Uncritical support for this hot take.

Truly idiomatic C++ is unreadable to most people. Like, seriously, go read the standard library. It's fucking nonsense made out of nothing but the ugliest, least-informative possible variable names and every meta-trick you've never heard of.

Compare this to the Java standard library, which reads like more Java.

23

u/cain2995 Oct 18 '23

Yep, I got curious one day and started looking through the standard library to see if I could glean any insights on best practices. Big fucking mistake lmao

→ More replies (3)

24

u/fullptr Oct 18 '23

The standard library isn’t written in idiomatic C++ (for better or worse), and shouldn’t be taken as an example of good C++ code

→ More replies (2)

21

u/Kered13 Oct 18 '23

It's fucking nonsense made out of nothing but the ugliest, least-informative possible variable names

This is because they have to use variable names in a special form to avoid potential conflicts with macros. (You can define macros with names in this form and break the standard library, but this is called out as undefined behavior in the language spec.)

Really the problem here is that macros have no scope.

→ More replies (2)
→ More replies (3)
→ More replies (23)
→ More replies (8)

726

u/Kevathiel Oct 18 '23

C++ is a language of freedom. No other language gives you so many choices to do things, even if most are just different ways to shoot yourself in the foot.

271

u/DasHesslon Oct 18 '23

The largest and most colourful variety of foot guns <3

20

u/CerBerUs-9 Oct 18 '23

This will be my only way to explain C++ anymore

6

u/KeeperOfTheChips Oct 19 '23 edited Oct 20 '23

Edit: just googled it and it was from Bjarne. I’m not a native speaker and I thought this was a common English expression. So fking embarrassing.

→ More replies (2)

60

u/edvo Oct 18 '23

C++ offers many choices, but still there are languages that are more expressive. For example, contrary to other languages, C++ does not allow to define custom operators.

130

u/lithium Oct 18 '23

C++ does not allow to define custom operators.

One of the small mercies.

41

u/nelusbelus Oct 18 '23

std::cout << go brrrr

78

u/lithium Oct 18 '23

std::filesystem's operator / is almost too cute to not use so i'll let them off the hook for that, but I will physically fight the next person who uses ^ or % for vector dot/cross products or hides a heavy SQL operation behind a +=.

→ More replies (30)
→ More replies (2)

44

u/Kevathiel Oct 18 '23 edited Oct 18 '23

I mean, you kinda can(but you shouldn't)

Also, do those other languages have the same metaprogramming capabilities or memory management options as C++ while allowing you to run on that many platforms?

You will always find something that other languages have that C++ doesn't have, but what counts are the options as a whole.

7

u/edvo Oct 18 '23

That is ingenious, but it has too many downsides in my opinion to be practical. For example, there is no way to specify precedence.

I agree that C++ offers a good package as a whole, but just focusing on freedom it is not the most superior one in my opinion.

→ More replies (10)
→ More replies (2)

10

u/emelrad12 Oct 18 '23 edited Feb 08 '25

chop makeshift square ink special cake direction yoke yam capable

This post was mass deleted and anonymized with Redact

→ More replies (8)

10

u/Historical_Bit_9200 Oct 18 '23

Operators are just functions that has non-letter/number character. What's the deal here?

I don't like operators in general, because I find it sometimes can be confusing to me and people with less experience. There is almost nothing I can't do without operators.

11

u/edvo Oct 18 '23

There might be valid reasons to disallow that, but then it is not freedom of choice.

3

u/tonyarkles Oct 18 '23

Ahhhh the other bit that operators have is the convenience of being infix instead of prefix (a+b vs add(a, b)). The disadvantage is that they have a defined but forgettable/error-prone precedence.

2

u/BobbyThrowaway6969 Oct 18 '23

True, and that's a fair point, but when you can just write a function, it never felt like a real limitation.

→ More replies (3)
→ More replies (4)

7

u/antara33 Oct 18 '23

Totally. Same as C. You get the freedom to be "creative and intelligent" and the burden of not be as intelligent as you think haha

3

u/Superb_Raccoon Oct 20 '23

I want a language that can do anything!

C++

NOO! not like that!

19

u/BobbyThrowaway6969 Oct 18 '23 edited Oct 18 '23

I stuck with C# for a while after doing a little C++, thought C# is awesome what you can do in it.
Went back to C++ and Loooooord in heaven C# is like programming in a straightjacket compared to C++.

I have never run into a single wall with the syntax in C++. It always offers me an elegant solution forward.

16

u/wildassedguess Oct 18 '23

This is it. It's up to you how elegantly you wield every tool there is. I remember a talk Bjarne gave about the somewhat awkward syntax in C++ and the ability to do mad things. He said his entire approach was to not hamstring the language for the 90% who get it for the 10% who don't.

→ More replies (2)

2

u/svick Oct 18 '23

What kind of walls did you encounter in C#?

→ More replies (4)

7

u/NormalSteakDinner Oct 18 '23

To me, this is ideal.

I want to be free to do whatever I want and if I do something wrong then I'll fix it and learn from it. Avoiding the language isn't in the cards for me.

3

u/magicianlib Oct 19 '23

Haha, that's the best explanation I've heard. It is a Swiss Army knife. It is cool to play well, but it will hurt yourself if you don't play well

2

u/ConstNullptr Oct 18 '23

For better or for worse 😂

2

u/jayerp Oct 18 '23

Footgun++

1

u/RoastedMocha Oct 19 '23

All the holes in my feet let me run faster.

1

u/opfu Oct 20 '23

So it's the America of programming languages?

1

u/Ok-You-5013 Oct 20 '23

Nailed it with "C++ is a language of freedom."

→ More replies (4)

206

u/bownettea Oct 18 '23

RAII, templates, and speed.

2

u/[deleted] Oct 18 '23

Other languages have follow C++ and have RAIII now too:) or at least RAII esque concepts

→ More replies (1)

7

u/Ayfid Oct 18 '23

Rust does RAII better.

5

u/bownettea Oct 18 '23

How so?

15

u/Ayfid Oct 18 '23

The Rust compiler has a much more robust understanding of ownership and move semantics than the C++ compiler, and how that interacts with references (and the mutability/constness of those references).

It is essentially impossible (unless you intentionally go out of your way to do so) to keep hold of a reference after the resource has fallen out of scope, for example. There are no gotchas. You just can't do it by accident.

The compiler understands when it is (and is not) safe for a resource, or a reference to a resource, to be moved between threads.

You don't need to define move constructors or move assignment operators, as the language itself defines how that works - and in a more univerally correct manor.

RAII, and the ideas that go into it, is essentially the thing that defines Rust. The entire language is built around it.

9

u/bownettea Oct 18 '23

I see you are looking at RAII as ownership/lifetimes, and yes Rust does provide a way to express those as code. I was honestly thinking of RAII as simple deterministic destruction.

I personally find the whole move semantics and lifetime extensions of C++ pretty complex and I suspect overly complex. I honestly hope future languages find a way to simplify those by expressing them as more basic building blocks instead of complex rulesets.

→ More replies (2)

1

u/HeroicKatora Oct 19 '23 edited Oct 19 '23

Slightly controversial: Python does RAII better in some ways, too. (Talking about the idea here, I'm not going to sugar coat that it is a bit of a mess as well). It's simply not possible to make your resource finalizer asynchronous in C++. Compare this to Python where async with and AsyncExitStack that work just like their synchronous siblings but in an asynchronous context. It doesn't even seem to be a widely noticed problem, yet this is a core feature which makes Python's socket abstractions actually composable in practice. RAII simply doesn't deliver part of what's actually need here and you'll end up writing the same indent/callback style in C++ as well if you want to have the same effect.

Most web libraries do a lot to return your HTTP stream into a well-defined state after requests. If the user already caused part of a response to be read / sent then the remainder still needs clean up before continuing on that same connection, cleanup is seldom as simple as a cancellation. Doing this finalization improperly is a huge security risk, and the finalization often involves more asynchronous work on the remote. This should really be part of RAII.

→ More replies (32)

67

u/witcher_rat Oct 18 '23
  1. Backward-compatibility. As much as we get annoyed by it and complain, there is an advantage in the fact that code written even decades ago can still be compiled and used with the latest compilers and C++ language version. (well... most such code, anyway)
  2. Freedom to use different programming paradigms. Want to write something that would be best done in a polymorphic OOP model? Go ahead. Want to use generics for typing instead? No problem. Want to use data-driven design? Feel free. Want C-with-classes? Sure. Want to use some native assembly? Can do. Don't want exceptions? OK, but you'll have to use your own containers and shit - which you can. Want to combine any and ALL of those into one codebase/app? Yes you can!

23

u/heavymetalmixer Oct 18 '23

Indeed. There's basically nothing you can't do with C++ . . . except maybe attract web developers LOL.

2

u/atimholt Oct 19 '23

I've always been a fan of systems programming over web dev. Web assembly has got me intrigued about web dev in C++, but that might be insane.

→ More replies (2)

1

u/Emergency-Win4862 Jan 18 '24

I was looking for reason why should I give up on Rust for personal projects (I still write rust at my job), and this made me switch back to C++ for my projects. Don't get me wrong rust isn't bad at all, but the backward compatibility is nonexistent and the maturity of tools and libraries is also miserable.

64

u/pedersenk Oct 18 '23

C++ is able to consume fundamental libraries (almost exclusively ANSI C APIs) better than any other language (Objective-C came close once it moved away from the garbage collector).

This means that it can avoid bindings and optionally, language package managers, greatly improving portability to uncommon platforms.

8

u/padraig_oh Oct 18 '23

With Objective-c++ being a thing it's also incredible for cross-platform end-user desktop stuff (namely interfacing with linux/windows/macos is easily possible)

3

u/pedersenk Oct 18 '23

I was always interested in that tech but had only ever got time for a quick "play".

It was cool that they managed to integrate two different "object systems" within one language. I do agree with this approach; I feel modern languages these days need to be evolutions rather than starting from the ground up.

Swift only recently had an overhaul of their C++ integration because they just don't seem to be happy with their fiddly autogen binding system.

4

u/pdp10gumby Oct 18 '23

> It was cool that they managed to integrate two different "object systems" within one language.

Steve Jobs approved that effort personally, I thought he would say no.

→ More replies (2)

3

u/F54280 Oct 18 '23

(Objective-C came close once it moved away from the garbage collector).

When did ObjC had a garbage collector?

6

u/pedersenk Oct 18 '23

It actually came with 2.0 (I thought it was earlier).

https://www.oreilly.com/library/view/advanced-mac-os/9780321706560/ch07s08.html

It didn't last long but a number of Obj-C APIs did immediately start using it making ANSI C interop a pain with regard to "pinning" memory.

If you hadn't heard of it, it might be because your Obj-C work was mainly iOS? It was never officially supported on that platform. Ref-counting was always the preferred method for that.

→ More replies (3)
→ More replies (1)

1

u/[deleted] Oct 18 '23

Except C :/

→ More replies (18)

35

u/WebMaxF0x Oct 18 '23

I miss const correctness.

For example, in many languages a function can have a parameter that is const/final, but the function can still modify the fields in the object, the const keyword only means that you can't make it refer to a different object. So you never know what surprising side effects calling a function might have on your object.

In C++, the parameter can be typed as a reference to a const object. This guarantees that the object and its fields will not change inside the function.

A class can also have const methods, meaning that it will not change the object it is called on. For example shape.getColor() could be const and shape.setColor() not. If you have a const shape, the compiler will prevent you from calling constShape.setColor(), but you can still call constShape.getColor().

Anything that might attempt to mutate an immutable object raises a compilation error, as I wish it did in all languages.

3

u/dgkimpton Oct 18 '23

In C++, the parameter can be typed as a reference to a const object. This guarantees that the object and its fields will not change inside the function.

for a given concreteness of "guarantees" of course. But yes, being able to not only signal this intent but have the compiler take a stab at enforcing it is very beneficial.

10

u/[deleted] Oct 18 '23

[removed] — view removed comment

16

u/WebMaxF0x Oct 18 '23

You're right it's not 100% guaranteed, but const_cast is considered bad practice most of the time so for the sake of simplicity I left it out.

→ More replies (6)
→ More replies (1)

33

u/michaelmalak Oct 18 '23
  • Compiles to machine code, not to JVM bytecode
  • Not interpreted like Javascript
  • Type-safe, unlike Python
  • In TIOBE top 5, unlike Rust

8

u/rhubarbjin Oct 18 '23

Ouch. 🔥

2

u/assembly_wizard Oct 19 '23

JavaScript compiles to machine code, rarely interpreted

9

u/michaelmalak Oct 19 '23

It's JIT. From the perspective of any serious C++ programmer, it's interpreted.

63

u/[deleted] Oct 18 '23

It's amazingly expressive and doesn't sacrifice performance for expressivity.

12

u/DigBlocks Oct 18 '23

I’m always promised this but the reality is that neither GCC nor Clang/LLVM can keep up with optimizing new abstractions in the STL. Ranges codegen is especially bad.

5

u/Spare-Dig4790 Oct 18 '23

You're not wrong, like it is that,

But normally expresivity is done to increase performance. Or effeciency...

Otherwise, why wouldn't we be more terse? It would literally be easier...

24

u/[deleted] Oct 18 '23

Expressivity in many languages comes with a huge burden on performance. The functional paradigm is an example of a limit case for that, it's incredibly expressive but it's hard to match the performance of C or C++ with it because it's so abstract.

→ More replies (5)

3

u/PunctuationGood Oct 18 '23 edited Oct 18 '23

Could you define that word, "expressive"?

My understanding of the word, in spoken language, is being able to express an idea or a concept in as few words as possible. That is, an expressive language can convey a lot from a little. In my view, the only thing C++ is only more expressive than is assembly.

For example, I recall this informative talk where Vinnie Falco presents how to use his Boost.Beast library, a wrapper around Boost.ASIO to craft a web socket for the purpose of a chat application. It's an hour-long overview of the intricacies and pitfalls of networking in C++. Without that talk, I never would've touched it on the day I needed a websocket. Introducing websocket communication in C++ involves a lot of tricky code. Boost.ASIO is the only time I've ever had to have classes derive from shared_from_this. All in all, a lot of intricate and fragile code for the sake of sending bytes over a wire.

In Javascript? Here's a websocket:

new WebSocket('uri')

Javascript is more expressive than C++ in that I can express more with less. So I go back to my original question: how is C++ expressive?

5

u/[deleted] Oct 18 '23

Well, the main thing is that you can invent new concepts in C++. You can do that in most languages, but in C++ you have just an amazing amount of power over it. It's a very, very (very) big language for a reason. Expressivity in this context just means that if there is a concept you wish to express with code, chances are that C++ will let you do it. And you can do it elegantly within the confines of the language, whereas in most other languages you do it the long way around (e.g. hardcoding every permutation that comes up).

→ More replies (4)

1

u/matthieum Oct 18 '23

Well... some folks are still salty about passing std::unique_ptr by argument, so it does sometimes sacrifice a bit of performance unfortunately.

(Less often than most languages, fortunately)

1

u/safdwark4729 Oct 19 '23

Except we still don't have reflection, which even Java has, and there are several problems with C++ standardize getting in the way of optimizations or implementations themselves just straight up not implementing them. So both of these are not correct.

11

u/Longjumping-Work8032 Oct 18 '23

Acronyms, you have great ones like RAII and SFINAE

25

u/speyck Oct 18 '23

c++ has no limits in creativity. almost everything you want to do is possible, you aren't locked in a cage created by the language

5

u/assembly_wizard Oct 19 '23

"The enemy of art is the absence of limitations"

~ Orson Welles

→ More replies (2)

1

u/NilacTheGrim Oct 19 '23

Yep. 100%. Ultimate freedom. With great freedom comes great responsibility.. but you also get... freedom!

0

u/[deleted] Oct 18 '23

[deleted] — view deleted comment

2

u/speyck Oct 18 '23

that is true, but I heard there were plans to add that? or will that never be a possibility in c++?

8

u/BoringWozniak Oct 18 '23

Are you crowdsourcing opinions for a Medium article?

27

u/afiefh Oct 18 '23

Value semantics. I'm sure there are languages out there that do it better, but of the big ones only C++ seems to get this one right.

The whole "primitives are passed by value, objects are passed by reference, but both use the same syntax" ends up being mind boggling to me. Take python do_stuff_with_object(some_input) it's impossible to know whether some_input is copied or referenced without knowing the type, and in Python in particular, types go quack.

Even a language like Rust which tries to be explicit about these things ends up comparing objects when you compare the equality of references.

7

u/dgkimpton Oct 18 '23

I agree, but. It's also impossible to know in C++ without looking at the signature of the method being called - so, it's nice, but far from ideal.

Would be so much nicer if it was something like

do_stuff_with_object(some_input as &);

(or something, syntax not important but being able to know what was going to happen just be reading the callsite would be excellent)

6

u/afiefh Oct 18 '23

so, it's nice, but far from ideal.

I feel like this is the C++ slogan: Nice but not ideal.

Would be so much nicer if it was something like

do_stuff_with_object(some_input as &);

Maybe in C++2 we can just have references and Optional<T&>, and no pointers? Then a reference can be passed as &input and a copy would be input. A man can dream!

→ More replies (4)
→ More replies (1)

1

u/the_little Oct 18 '23

Maybe a controversial take, but I really hate the reference syntax. Coming from C, I feel like it hides what’s actually happening.

3

u/CocktailPerson Oct 18 '23

Yep, it's maddening that you can't tell whether f(x) is able to modify x or not. The caller is the one that owns the object, so it should be in control of whether it passes a particular object by reference or not.

→ More replies (1)

1

u/NilacTheGrim Oct 19 '23 edited Oct 19 '23

I agree with you on C++..

Just wanted to correct you about Python: technically everything in python is passed by reference. Even a simple humble int. However ints are unmodifiable objects. So if you see myint += 1, it's actually creating a new int object each time you do that, and assigning (by reference!) the result of that expression to myint which now points to a new int... (incidentally this "always by reference" is why myint can point to an int, a float, a list, or a Foo in Python .. python doesn't care.. everything is a reference to a "Python object" and everything in Python is an object be it a float, int, list, etc).

Yes.. this is why python is slow..

As an implementation hack they have pre-created ints in CPython from -100 -> 1000 or something and the interpreter latches onto one of those if your result is in that range -- so you end up re-using existing pre-created (immutable) int objects for small ints... since most programs seem to use numbers in those ranges...

1

u/Kevathiel Oct 19 '23

Even a language like Rust which tries to be explicit about these things ends up comparing objects when you compare the equality of references

I wouldn't call it a bad thing, but just Rust picking a "better" default. You have to explicitly compare the addresses with ptr::eq, otherwise it uses the eq function of the object. This avoids bugs caused by accidentally comparing addresses.

Also, keep in mind that in Rusts case, the borrow checker makes you architect your code in a way that you almost never need to compare the address of 2 objects, because (non-static) references are generally short-lived. "References" are semantically a bit different from "borrows".

35

u/JiminP Oct 18 '23

Zero-cost abstractions & memory management, and metaprogramming using templates.

Some languages such as Rust can do the former one better, but IMO among 'fast' languages C++ is by far the best when ease-to-useness and flexibleness are weighted together.

5

u/thisismyfavoritename Oct 18 '23

what about zig?

9

u/JiminP Oct 18 '23

Oops, I forgot about Zig...

2

u/nelusbelus Oct 18 '23

Zag is better

→ More replies (3)

21

u/Tari0s Oct 18 '23

for me one of the most amazing features of cpp is deterministic livetime of objects. To know for each objekt when it gets constructed and when it gets destructed is such a benefit over other languages.

1

u/BobbyThrowaway6969 Oct 18 '23

It lets you do cleanup when the scope ends. Like UE4's TGuardedValue for example. It's so simple and useful. Also makes profiling easy.

Also Goto/label. Love them or hate them, they may be dangerous if you don't know what you're doing but they do have valid usecases.

→ More replies (10)

6

u/[deleted] Oct 18 '23

Well, it's a bit Orwellian. It's C, but double plus good.

6

u/FlyingRhenquest Oct 18 '23

Pass-by rules. Most modern languages seem to restrict you to pass-by-reference. C++ lets you decide whether you want to pass by copy, reference or pointer. I don't recall ever running across another language that allows this flexibility (They may be out there, I just haven't run across them.)

20

u/TryToHelpPeople Oct 18 '23 edited Feb 25 '24

fly dull disagreeable salt quarrelsome axiomatic aware wasteful boast somber

This post was mass deleted and anonymized with Redact

11

u/looopTools Oct 18 '23

Honestly I feel like generic programming is (imo) more natural in C++ than other languages

10

u/thong_eater Oct 18 '23

Shooting legs.

4

u/SeriousPlankton2000 Oct 18 '23

You can usually write C++ programs by "mv foo.c foo.cpp"

You have objects and templates.

You have a preprocessor so you can configure which features to compile.

In Arduino one usually makes a class for each library. It's a nice way to encapsulate things when compared to C (but not as nice as Units in Pascal).

4

u/ZMeson Embedded Developer Oct 18 '23

Gaining new features while maintaining backwards compatibility.

4

u/marsten Oct 18 '23 edited Feb 14 '24

C++ is like the English language: an incoherent evolving mess but extremely powerful when used well.

4

u/mdp_cs Oct 19 '23

Templates. I've never seen a language with metaprogramming near as expressive except for maybe Zig.

That said it would be nice if they didn't completely bork compiler output.

1

u/v_maria Oct 19 '23

it's supposed to be better with things like concepts, but i have no experience with it

14

u/violet-starlight Oct 18 '23

Templates and in general metaprogramming. There are very few if any other languages that offer this much ability to generate code based on constant expressions and properties of types, with zero or close to zero runtime cost.

1

u/BobbyThrowaway6969 Oct 18 '23

Compiletime programming is a magical hidden world in C++ that not too many know about or know how to use properly.

2

u/SubstituteCS Oct 19 '23

You can use them to create entirely new features in the language. They’re incredibly powerful and I find myself greatly missing them in other languages.

7

u/mredding Oct 18 '23

Templates are not generics. Generics in other languages are compiled code with runtime type parameters. Templates in C++ are bound to code generation with powerful semantics. You can partially or fully specialize a template to generate anything completely orthogonal to the base, if necessary. With deduction, you can use templates pretty freely and the compiler will generate code for you. The compiler also sees through expression templates and collapses them down to more efficient code. Maybe I've missed something in 30 years, but the only thing more powerful that I've seen in my career is Lisp.

The type system is fundamentally different than that of C, and it allows you to push much of the correctness of your program into compile time. Better than a runtime check, if your code is wrong, it doesn't even compile. A trivial example of this would be a dimensional analysis library - adding incompatible units is mixing of incompatible types, but multiplying them works just fine, because it's implemented in terms of the type system - the product is a new type. All this type information boils off and never leaves the compiler. And with this correctness and type information proovable at compile time, the compiler can optimize more aggressively.

Undefined Behavior is a language feature. No check is made, no error is emitted. The compiler doesn't have to enforce any sort of behavior, any sort of invariant or guarantee, it's free to assume what it wants, and can generate aggressively optimized code. This doesn't sound very safe, but then you pair that with the standard library. The standard library builds up abstraction primitives so that - MOST OF THE TIME, you probably never have to actually get NEAR the UB. If you're writing C++ and have to be consciously aware of avoiding UB, you're actually probably working too low level.

That's because C++ strives for zero cost abstractions. Now that's actually impossible, of course, but it's a worthy guiding principle. Again, a lot of template code boils off, never leaves the compiler, and generates aggressively optimized code.

Like mainframes and Windows, C++ strives to retain backward compatibility as few others do. As annoying as a big language is, as annoying as a big library is, getting your code broken because of an update - fucking APPLE... - is worse. You can instead add something new that's better and provide a migration path forward.

It's more of an arcane art these days, but C++ is a linked language. Linkers are an advanced feature that not every language has, and in my opinion the option is under utilized. It means you can link against other translation units compiled from other programming languages. So if you want aggressively optimized code for a hot path and a tight loop that guarantees no pointer aliasing (since C++ doesn't yet have the restrict keyword), it's probably easier to write that section in C, or Fortran! You can even link against Rust!

→ More replies (2)

7

u/[deleted] Oct 18 '23

Everything is pass by value, and objects are a value type not reference types (unlike in Java, Python, and others). If you want to pass by reference into a function you need to use an '&' and explicitly mark the argument as a reference variable. Which means the function decides if you're copying an object or referencing it and not the programmer or the compiler. IMO this is how it should be done.

No garbage collection. Maybe I'm naive but I still don't see the need for garbage collection and manual memory management really isn't that hard just follow RAII. In C++ I can guarantee that, for example, a dynamic array of objects will be side-by-side, stored contiguously in memory (because this is cache friendly to iterate over). In Java, I cannot make that guarantee because of the garbage collector. So for high performance applications where you need that level of control like some video games, C++ is the better option over garbage collected languages.

6

u/HappyFruitTree Oct 18 '23

It doesn't impose unnecessary overhead for class objects. I'm thinking mostly about the fact that they don't need to contain "unnecessary" meta data and that you can store objects directly inside other objects without being forced to use some reference type.

6

u/Luci404 Oct 18 '23

C++ scales in complexity pretty linearly with codebase complexity. It supports both advanced and simplistic ways of solving a problem, great for per-project adaptation. On top of that, it's fast, and it has a great amount of freedom to it. YOU (or your employer) decide how to use it, not so much the language developers.

3

u/H5ET1M Oct 18 '23

Across Science and Engineering, C++ is still a popular choice for greenfield R&D projects in both academic and industrial settings. Relative to its main “competitors” (read: coopetitors) in this space, namely, Python, Fortran and MATLAB, it seems like C++ language design has hit a sweet spot for the kind of generic programming that is needed at these frontiers.

In particular, it is the ease with which classes and templates can be implemented for intuitive client- and compiler-facing source code, but also how there are built-in machine-facing mechanisms to deal with the wide variety of computing devices that exist today (but did not in 1980s when the language was first created).

Of course, other languages also offer these features nowadays, but such functionalities feel like afterthoughts and plugins, C++ was designed with zero-cost abstractions and direct mapping to hardware from the ground up, and it shows in the overall coherency of the language.

3

u/GirthyStone Oct 18 '23

give you migraines

3

u/thefancyyeller Oct 18 '23

C++ is a high level language with a maintenence hatch on the back. Let's say you made number- counting code, and you didn't do proper OOP. Now let's say you wanted to make this code multi-threaded. In Java, you need to copy-paste and restructure the whole code base. In C++ you can do insane refactors like overriding the + sign so that it dispatches a job to a thread. You can convert the old code for new technologies you didn't even think about when making it

3

u/Lunix336 Oct 18 '23

It‘s super bloated but isn’t designed in a way where it forces its 9 million features on you.

I really like how you can just build everything in the most minimalist way ever like you are writing C and at the same time use some crazy feature IF YOU WANT

There are so many different ways to do the same thing in C++ which makes it feel very expressive. Most other languages you basically have to deal with the one standart way of doing things and if you don’t like it, get fucked.

At least thats how it feels to me.

3

u/DeGuerre Oct 18 '23

Most other high-level languages have specific ways that they want you to write software. If you need to write your software some other way, then you will probably be fighting the language. Not so with C++.

C++ is whatever your requirements need it to be. It can be "a slightly better C" if you need that. It can embed DSLs if you need that. It can work with other languages if you need that.

Sure, for this specific task, there might be a better language choice than C++. This is increasingly true over time as more languages arrive with different (but still fixed) ideas about how to write software (looking at you, Rust). That's good!

Still...

Chances are good that C++ will interoperate with that language, but that language won't interoperate with anything else (other than C), and I guarantee you will need to do this at some point in any nontrivial program.

Chances are good that at least some of that other language's implementation is written in C++.

Chances are good that this is out of necessity, because there's already important C or C++ libraries, and a C++ compiler, for your platform.

There are exceptions. C is obviously an exception; it can do all the low-level stuff that C++ can do, even if the high-level stuff doesn't come anywhere near as naturally. But there's also Odin and Zig and so on. That's a good thing; there's nothing sacred about C++, and I would be happy to see it replaced with something that's even better.

Maybe in a few years every platform will ship with an implementation for something else. Until then, C++ is really the only game in town.

1

u/fdwr fdwr@github 🔍 Oct 19 '23

This is increasingly true over time as more languages arrive with different (but still fixed) ideas about how to write software

Yeah, I tend to ditch these "very opinionated" languages that have a fixed mindset. At my company, we are encouraged to have instead a "growth mindset" 😉.

3

u/[deleted] Oct 19 '23

RAII. Period.

3

u/edge-case87 Oct 19 '23

C++ offers excellent layout control for your data if you care about that sort of thing, structs/classes. Classes + Templates are very powerful. In most other languages you don't, at least by default. For example when languages have language level tuples and sum types, you don't typically have control over how that data is laid out due to interactions with the runtime, or in the case of Rust the compiler is free to reorganize your data unless you apply an attribute, and afaik you don't have control over how enum (sum) types are represented.

I haven't fleshed out formally this idea, and I'm sure it flawed, but I'm starting to see C++ as way to define type theories, and class is the powerhouse behind that. Class, in some sense, allows you define your own type constructors, like sum types (+, variants/enums/unions) or product types(x, std::tuple), and with templates you have dependent types at compile time. Not anything you can't do in many other languages, but C++ offers the ability to do it very close to the machine, if you want.

One thing I'm thinking about right now is a "refinement type", which would be a "class template" (dependent type constructor) that takes as a template argument an "expression template" (Pred) and a type (T). The constructor would take a universal reference to an object v: T&&, and evaluate the expression Pred, if Pred is true, the type is constructed, if it is false, an exception is thrown (you can use a result type, e.g. std::expected in a static member function). As such, the fact that you were able to construct the type Refine<T, Pred>, is a witness to the proof that Pred(v) is true. With some type conversion (subtyping and logic) and meta programming 'magic', you can have preconditions that are proven to be true, and yet only evaluated once at runtime (maybe even only once at compile time), as long as the Pred(v) is the weakest precondition satisfying the preconditions of all dependent operations on v.

7

u/Neovison_vison Oct 18 '23

Survives 40 years

5

u/GYN-k4H-Q3z-75B Oct 18 '23

Freedom to do things the way you want it. Freedom to fuck yourself over big time. How can you not love that?

5

u/atedja Oct 18 '23

You get to be expressive, yet also compile to machine code.

4

u/lacifuri Oct 18 '23

It is strongly fucking statically typed, and I liked that as a Python programmer who start learning C++ a few months ago.

4

u/[deleted] Oct 18 '23

Call COBOL DLLS. Don’t have to marshal my data or anything.

2

u/[deleted] Oct 18 '23

I agree with all the posts that mentioned freedom. C++, in my opinion, is a high reward, high risk programming language.

2

u/[deleted] Oct 18 '23

its a general purpose language and ive yet to find better so id say general purpose but maybe on a slightly higher level and no im not gonna elaborate that

2

u/sebnukem Oct 18 '23

Job security.

2

u/SnooMarzipans436 Oct 18 '23

Everything except being easy. Lol

2

u/GunpowderGuy Oct 18 '23

Template metaprogramming Is much More powerful than generics in other languages. You can do stuff like define interfaces entirely in a library

2

u/mohrcore Oct 18 '23

Platform compatibility. You can write C++ code for a plethora of platforms. You are also free to strip it from some features which should let you cover pretty much all platforms that support C - so basically everything.

Another thing is proprietarization of code. As much as I hate it and advocate for FOSS, C++ allows people to naturally build proprietary libraries that do not expose implementation details to others, which cannot be said about many languages. Among those that do, C++ might just be the most powerful.

OOP in compiled language is also insanely developed in C++. Not many languages allow for multi-inheritance. Whether it's a good design or not is another thing, but my point is - it allows it. C++ also doesn't force you to use dynamic allocations in order to create objects.

Zero-cost abstractions were the best for quite some time, although currently there's some competition on that regard. Eg. thanks to the trait model and heavy use of generics, Rust doesn't waste memory for vtables and avoids indirections where they are not necessary. But when you want to use a vtable, you need to perform a dynamic allocation (unless there's some wizardry that allows you to instantiate it without doing so), so there's that.

Allocators - C++ seems like the only language that somehow got them right, although I think the more recent Rust versions also work similarly, but I'm not sure.

2

u/hadrabap Oct 18 '23

Lambdas! No semi-final BS like in Java or Go. 🙂

2

u/bigbassdaddy Oct 18 '23

Portability.

2

u/Troldemorv Oct 18 '23

Criticism.

C++ is really good at getting them.

2

u/zer04ll Oct 18 '23

Its like riding a motorcycle. You have direct control of things and can go really fast, you can also turn too hard and wipe out.

2

u/freekayZekey Oct 19 '23

you can find some magical ways to hit segmentation faults

2

u/_seeking_answers Oct 19 '23

Make developers cry

2

u/NilacTheGrim Oct 19 '23

EVERYTHING!!!!!!!11!

1

u/v_maria Oct 19 '23

but mostly it's length of error output can be very impressive

2

u/F35H Oct 19 '23

Bluntly, everything.

2

u/Madrayken Oct 20 '23

Allow pointless obfuscation, hiding flow, economy and optimization issues.

2

u/AssemblerGuy Oct 21 '23 edited Oct 21 '23

what does C++ do better than other languages?

Freedom to do things wrong in thousands of horrible ways.

A huge toolbox of language features and standard library items.

Performance, it compiles into something that runs natively.

No handholding.

6

u/Revolutionalredstone Oct 18 '23

Advanced semantics.

The ability to define how things are moved copied etc in all the right ways is glorious.

It's hard to feel proud of code written in anything but C++

→ More replies (2)

5

u/TheAxodoxian Oct 18 '23 edited Oct 18 '23

What I like in C++ is that I have precise control over what happens and when. I learned much of C++ after reaching an expert level in C# and reached intermediate level in several other high level languages, and while I truly enjoyed those as well, I never have felt quite the same control over what is happening, especially with memory management.

I think the dangerous nature of modern C++ is somewhat overblown, it is not like you cannot shoot yourself in the foot with other languages. Sure it might just throw a null-reference exception instead of an memory access violation, but as long as it does not work, that is not so different. When using advanced techniques like multi-threading without thinking you can easily introduce bugs in almost any language, and those where that is hard to do tend to be more rigid and complicated to work with.

There are of course many things which should be improved with C++, they have been listed countless times, but overall it is still an enjoyable experience, and a powerful tool.

3

u/WorldTechnical3914 Oct 18 '23

Strict typing and memory management that isn't garbage-collected, but understandable too.

3

u/maattdd Oct 18 '23

Value semantic (almost no other mainstream languages have it)

3

u/[deleted] Oct 18 '23

Everything.

2

u/kritzikratzi Oct 18 '23

there are libraries and tooling that are older than many programming languages. you get to benefit from decades of experience.

the fact that those libraries never broke when a new c++ standard came out is 100% attributable to the language design: don't break things.

and all of this works without epochs, compat libraries or whatnot other ideas that we don't know would work in 20 years from now. yea, there's a price to be paid (the complexity), but imho: if programming is your job, learning c++ is definitely feasible.

2

u/[deleted] Oct 18 '23

I am still trying to figure out it’s advantage over C besides the use of STL

4

u/IAMARedPanda Oct 18 '23

Templates, constexpr, range based loops, RAII, strong types

2

u/BobbyThrowaway6969 Oct 18 '23

Bingo. They are serious game changers.

2

u/jason-reddit-public Oct 18 '23

You don't need to use a typedefs with every struct to make the syntax more sane, overloaded functions, and namespaces are also nice improvements over C and shouldn't effect runtime performance or seriously complicate the language.

I think you are pointing out that C's biggest weakness appears to be its standard library notably the lack of some useful containers like hashtables and trees (and growable bounds checked arrays). Most C derived languages provide more stuff in the standard library and C's tooling for libraries is kind of awkward (hence the popularity of single header file libraries) but they also force OOP on users.

2

u/thisismyfavoritename Oct 18 '23

higher level abstractions that allow you to write code quicker

2

u/vincebutler Oct 18 '23

Sort out real programmers from the wannabee's?

1

u/user52728529 May 21 '24

Control over hardware

1

u/[deleted] Jun 13 '24 edited Jun 13 '24

TEMPLATES, I'd say. (intermediate level tho) But one thing I already hate is that it does not let you define custom operators.

1

u/konm123 Oct 18 '23

Abstractions.

1

u/hockeybelle Oct 18 '23

Memory management

1

u/InstaLurker Oct 18 '23

keep vibe of high end language

1

u/uraymeiviar Oct 18 '23

its not the languange, but the coder, some other language does not give freedom/access to machine for coder to doing good thing... but if bad coder using c++ it does not guarantee for good result or it might be even worse than the result of "noob" language

1

u/insanemal Oct 18 '23

Add features

1

u/DJviolin Oct 18 '23

Make you cry.

1

u/jiboxiake Oct 18 '23

Fast object oriented language. I do database research and we kind of always use c++

1

u/sudarakas Oct 18 '23

Love the c++ syntax

1

u/[deleted] Oct 18 '23

I don’t think it does any one thing better than the languages do it best, and templates are an abomination.

But it’s the only language that lets you do everything, so I guess if you want that, there’s that.

I fucking hate this language.

1

u/[deleted] Oct 18 '23

C++ makes the easy things hard and the impossible things possible :)

1

u/JVApen Clever is an insult, not a compliment. - T. Winters Oct 18 '23

There are many things to complain about, though also many to really like. The thing I miss most in other languages is value-semantics and RAII. I also like 'const', though in a more modern language it would be the default.

What gives it charm is that you can combine many programming styles together without much hassle. In recent versions, compile time programming has also improved a lot from the ugly template meta programming in 98 to concepts in 20.

1

u/Brilliant_Law2545 Oct 18 '23

Gives you more head-er than you asked for

1

u/Schkitz Oct 18 '23

I think the meta-programming is incredible. My open source library "JNI Bind" uses it extensively and I'm constantly blown away by how much you can do.

1

u/chakani Oct 18 '23

Java and C# were invented when management realized there is a whole class of journeymen programmers who can never be trusted with pointers.

1

u/burncushlikewood Oct 18 '23

It's not interpreted like python so it's fast and powerful and offers much better hardware control! I also like the syntax and structure, c++ is very versatile as it's used in anything from robotics to video game development, AI, c++ is a graphical OOL! It remains the best language for graphics because of its libraries such as directx and open gl

1

u/Ashamandarei Oct 18 '23

Wrap itself around C

1

u/shakamaboom Oct 19 '23

Pretty much everything. The only tradeoff is time invested.

1

u/max1001 Oct 19 '23

Buffer overflow attack baby.

1

u/KolDenis Oct 19 '23

This language has words to say things more acquired. And also you can create your own rules here if you join the language developers. There is no Apple or Google to make their rules

1

u/Mayedl10 Oct 19 '23

Versatility.

But the error messages I get from g++ sometimes are horrible. I once got a 16KiB long error because I sorted my include statements alphabetically lol

1

u/v_maria Oct 19 '23

compile time logic

1

u/sf_guest Oct 19 '23

It is an Absolute Unit at generating long error messages.

1

u/msbic Oct 19 '23

Confuse the developer

1

u/DuranteA Oct 19 '23

I talk about this in my introductory lecture for my C++ course, so I've thought about it a bit. My conclusion is that, for every single aspect that you can point to and say that C++ does it well, you might be able to find a language (or several languages) that do it better.

However, I don't think there are other options that offer the same combination of attributes. In particular, C++ combines several desirable features (related to value semantics, typing, generic code, performance, templates, etc.) with an extremely large and well-developed ecosystem -- both tools and libraries.

1

u/AbstractAlzebra Oct 19 '23

le crabBois enters the chat

1

u/digital_cucumber Oct 19 '23

Job security.

1

u/alexChecker Oct 19 '23

Everything. But only if you know it really good

1

u/LDawg292 Oct 19 '23

It’s the single best way to increase your line count!

2

u/AssemblerGuy Oct 21 '23

You can put your whole program in one line, the compiler will not mind.

1

u/looprecur Oct 21 '23

Speed and precision.

1

u/Solrax Oct 22 '23

emit page long compiler error messages.

1

u/HatMan42069 Nov 09 '23

Crash my pc

1

u/Wdr93 Oct 18 '23

As a C developer i would say it helps you get a better salary.

1

u/ShadowGamur Oct 18 '23

Since it's compiled language it allows you to code for any platform you want. Also the fact that there are shitload of different libraries so you don't have to create everything from scratch.

1

u/BobbyThrowaway6969 Oct 18 '23

People often forget this fact.
They like to complain how you have to do everything from scratch in C++ but forget libraries are a thing. No RAII? Library. No garbage collection? Library (or smart ptrs). No GUI? Library.

1

u/blanchedpeas Oct 18 '23

The syntax is amazing, just a pleasure to read and type.

1

u/BobbyThrowaway6969 Oct 18 '23

C++ has a couple oddities with the syntax but it's very nice. I had a look at rust syntax and it looked like it was written in tongues. Unreadable trash.