r/AskProgramming • • May 27 '20

Why is C++ such a controversial language?

Linus Torvalds said " C++ is a horrible language. It's made more horrible by the fact that a lot of substandard programmers use it". Jonathan Blow, a game developer said "C++ is a weird mess. My new language would increase productivity 50 to 80% over it". I have also had teachers and met other coders who seem to want to avoid C++ like the plague. Why does C++ generate more controversy than other languages?

105 Upvotes

107 comments sorted by

54

u/Astarothsito May 27 '20 edited May 28 '20

When people approach a big language like C++ with fear instead of curiosity the most likely result is that a lot of people would hate the language.

Also, the part that C++ is heavily criticized by big personalities like Linus Torvalds makes a lot of people cargo cult around it, instead of learning the reasons why. Some of the critics are old, some are based in misconceptions about C++ like "C++ is a weird mess. My new language would increase productivity 50 to 80% over it" well yes, but only if your problem is in the same set of the new language targets. And that part of "My new language", C++ is not made by one person anymore, C++ doesn't serve the interest of a single person or a single company but instead a large and diverse group of developers in all kind of industries. A single person can't design a language for the same user group as C++ anymore (and also ISO standardization is a big plus in some industries).

The story of C++ is interesting because in spite of everything against it, it is still one of the most successful languages. A lot of big personalities trash talk about C++, even big companies like sun and ibm did their part to trash talk about C++ explicitly, some universities care a lot about what ""the industry" says and listened to them making professors and new students hate the language as well, and even C++ didn't have a big financial investment.

So, I think is controversial because of fear and disinformation. "C++ is there because we can build good systems for people" - Bjarne

23

u/CoffeeTableEspresso May 27 '20

To be fair to Torvalds, he said those things some 20 years ago.

He's not nearly as critical of C++ anymore as he once was.

8

u/OnlySeesLastSentence May 28 '20

in despite of

You'd either say "in spite of" or "despite"

1

u/AnotherEuroWanker May 28 '20

Also, I suspect that when you get familiar with them, you discover that all languages end up being a mess.

They all have their little horrors, while also being good enough for whatever they're used for. Until someone comes with the next best thing, and a new batch of horrors.

1

u/SV-97 May 28 '20

When people approach a big language like C++ with fear instead of curiosity the most likely result is that a lot of people would hate the language.

Tbh you can also approach C++ with curiosity and hate the language.

24

u/[deleted] May 27 '20

Google: Did you mean “How to start war in r/AskProgramming”?

68

u/[deleted] May 27 '20 edited May 27 '20

The answer is C++ has a wide group of programmers who are aware of it and all of them have very different preferred styles of programming an unconscious biases because of it. If you pardon me I'm going to talk in the language of this talk on the perverts guide to programming languages. So C was, in the beginning, a language that was primarily chosen for its productivity it was a more productive assembler and thus the programmers who chose it were mostly psychopathic not really interested in rules but mostly just interested in getting the job done. C doesn't have some kind of coherent mental model. C++ is a language that came along to try to add abstractions to C in order to make it easier to express ideas.C++ is a hysterical fork of C. Philosophically, this is more to like if python was implemented on top of PHP. Afterward, C changed because languages became more friendly in general and the crowd around C became more interested in proving they could deal with the lack of expressiveness and handholding in C. In the language of the perverts guide, C became masochistic. C++ has due to its long history lots more ceremony and tasks that don't appear in say python and ruby and thus attracts lots of obsessional programmers.

So, yea C++ is a hysterical fork of a masochistic language that used to be psychopathic and itself is more obsessional because of the march of time. All these 4 groups of people fight about C++. The psychopaths find the focus on abstraction pointless. The masochists can't show how disciplined they are by using new abstractions so they don't like them. The obsessives are focused on the minutiae of the language to the annoyance of everyone and the hysterical are busy making a statically typed python.

Edit: Woot! Thanks for the gold kind stranger. Hang Loose!

15

u/Veedrac May 27 '20

It's wrong to talk about C++'s issues as coming from C, since the majority of what's bad about C++ is new. C's shallow copy semantics are industry-standard and fine. C++'s deep copy semantics are almost unique and terrible, and its patch over it with move semantics is almost unique and also terrible. C has no templates; C++ does, and their bad, buggy, slow implementations are a large source of the ire C++ gets. C has weak typing in a limited and at least tractable manner, C++ extended this to be practically universal, and then added overloading which made the problem way worse. C has a fairly simple scope management problem; C++ added ADL. C's random library consists of a sum total of like two bad functions built at a time people mostly didn't know better; C++'s <random> on the other hand is new, also terrible, and extremely complicated for no valid reason.

By no means is that an exhaustive list. There are a small number of things that can legitimately be blamed on C, like header files and arithmetic, but it pales in scope compared to what C++ brought to the table.

5

u/phoeen May 27 '20

value semantics paired with destructors is such a joy to use. currently i have to use a bit of c# and wow its like everything is a shared pointer to non const objects. when shared by mutliple threads it calls for race conditions. then you want to make 2 distinct copies and struggle while doing so cause well everthing is a reference.

i may be biased because i know c++ quite well and i am not so familiar with c# and its idioms, but boy do i miss value semantics.

3

u/Veedrac May 27 '20 edited May 27 '20

RAII is fine, I never said otherwise, but you can (and should) have it while keeping shallow copies. See Rust for an example, though C++ would need to use something more like an invalidate method since it wants to move objects out of pointers. This would replace the copy and move assignment operators as well as the move constructor, while being simpler than any of those individually, and also preserving the many advantages of shallow copies. You also wouldn't need rvalue references.

4

u/balefrost May 27 '20

C's shallow copy semantics are industry-standard and fine. C++'s deep copy semantics are almost unique and terrible, and its patch over it with move semantics is almost unique and also terrible.

I guess I don't follow this, but it's been a while since I did any C or C++.

IIRC, in C, structs that are passed by-value are effectively copied byte-for-byte, making them deep copies. That is, if struct A contains a member of type struct B, then passing an A by-value will also create a full copy of the nested B. To get a shallow copy, you need to change your data structure to use pointers. Then the pointers themselves are copied exactly, but the pointed-to data is not cloned.

IIRC, C++ has the same default behavior. The difference is that C++ also lets you override the copy behavior on a type-by-type basis, so you can in fact have types that deep copy some fields and shallow copy other fields.

But it's been a while, so I might be wrong, or I don't understand what you're pointing at.

C has a fairly simple scope management problem; C++ added ADL.

I had never heard of ADLs before, but I've certainly used them since the std library uses them. That does seem like a bizarre feature. It seems like it's a warty solution to the problem that arose from intersecting features - namespaces and operator overloading.

I'd say that namespaces are a good idea in principle. I'd say that the lack of namespaces is a downside of C. But the C++ implementation isn't perfect.

9

u/CoffeeTableEspresso May 27 '20

You're right about the structs being copied by value in C. But if you have, say, a pointer to B instead of just B inside your struct A, the copy of A will point to the same place (since you just copy the pointer itself byte for byte, not what it points to.)

THAT'S what people mean when they say C has shallow copying.

A deep copy would recursively follow all the pointers in A and copy whatever those are pointing to as well.

2

u/Veedrac May 27 '20

The other reply explains the deep/shallow copy distinction; I just want to emphasize here that shallow copies are nigh universal. C, Java, Python, Haskell, Rust, JS, Go, it's actually hard to think of languages that don't shallow copy.

I'd say that namespaces are a good idea in principle. I'd say that the lack of namespaces is a downside of C.

I agree with this.

3

u/balefrost May 27 '20

I still don't understand the distinction that you're making between C and C++. If I make a C++ class that has pointer members and that has no custom copy constructor or assignment operator, it behaves the same as a C struct. Passing an instance of such a class by-value to a function would cause the runtime to make a "shallow" copy.

C++ just allows further customization than C. A particular class can be specified to do deep copies, e.g. std::vector. And that's seems like reasonable behavior for vector. It would be more surprising for vector copies to share the backing array. If I want to avoid the copy, I can always use a pointer or a ref parameter.

So sure, if you want to say that C does shallow copies, that's fine. But then C++ also does shallow copied by default. C++ just gives you the ability to override that default behavior, while C does not.

3

u/Veedrac May 28 '20 edited May 28 '20

So in C++ you have the choice between unmanaged C-like types, typically called ‘POD’ types, or managed ‘proper’ C++ types. It's true that POD types inherit C's shallow copy semantics. However, instead of building on this to create managed types, you mention std::vector, they made a second meaning for assignment, aka. ‘run a user-specified function that does a deep copy’.

What they should have done is build on what was already there, since C's assignment is already correct, and simply add a function that is called whenever an object is moved from without replacement in a way that can't be statically tracked by the compiler, to allow tracking which std::vectors are invalid (C++ calls this ‘moved-from’) or not. Deep copies do not belong in the assignment operator.

There are many advantages of shallow copy semantics, from performance to correctness to better C interop, but as a quick non-exhaustive example, for std::vector this would mean that instead of writing a copy assignment operator, a move assignment operator, and a move constructor, you'd have invalidate() { this.ptr = nullptr; }. (Note that you can keep the copy constructor, since that's a reasonable API for duplicating values.)

1

u/MoTTs_ May 28 '20 edited May 28 '20

It's true that POD types inherit C's shallow copy semantics.

Personally I still don't agree with your characterization here.

struct A {
  int a_value = 42;
};

struct B {
  A a;
  int b_value = 14;
};

struct C {
  B b;
  int c_value = 5;
};

int main() {
  C c_original;
  C c_deep_copy = c_original;
  c_original.b.a.a_value = 1;

  std::cout << c_original.b.a.a_value << "\n"; // 1
  std::cout << c_deep_copy.b.a.a_value << "\n"; // 42
}

Whether C or C++, assignment does a deep memberwise copy of values. It yields a result that is a full and independent copy of the original. If a user-defined type that *we* write owns a resource -- whether that be a pointer to memory, or a file handle, or a lock, or whatever -- then it's up to us to maintain that same "full and independent copy" behavior.

2

u/Veedrac May 28 '20 edited May 28 '20

That's still a shallow copy, because it does the same thing as memcpy(&c_deep_copy, &c_original, sizeof C). C contains B contains A by value, as a flat, contiguous region of bytes; that's what ‘shallow’ means. Deep structures are those with pointers, or other referenced resources they don't contain.

Whether C or C++, assignment does a deep memberwise copy of values. It yields a result that is a full and independent copy of the original.

This is only true if you consider all C structures to be flat, but clearly many of them contain pointers, and clearly at least some of those are intended to be owned.

You are right that for truly flat structures, there is no difference between a deep or shallow copy.

1

u/[deleted] May 28 '20 edited May 28 '20

assignment does a deep memberwise copy of values

I think people are very confused about deep copying, member wise copying, and shallow copying.

Member wise copying is shallow copying. What C does is the equivalent of memcpy(&c_deep_copy, &c_original, sizeof(C); Even calling it "member wise" is a bit misleading, because its a byte-for-byte copy over the storage of the original, to the storage of the destination.

A true deep copy often will have a C* CopyC(struct C *src, struct C *dst); function it will do whatever the appropriate thing to do for type struct C, for example if it has a memory buffer dynamically allocated with malloc(), the copy function may do another malloc() of the same size and memcpy over the bytes in the original buffer. This ensures both the original and the copy, while identical at first, may diverge by having different values in the buffer. There are cases where it makes sense to not copy the buffer, if it contains invariant data of use to both copies of C, then you find a way to reference count the resource so it will eventually be freed.

1

u/[deleted] May 28 '20

IIRC, in C, structs that are passed by-value are effectively copied byte-for-byte, making them deep copies. This is correct. And copying structs with pointers to things like memory buffers that eventually need to be free'd is where things got really hairy in C, unless you had well considered ownership semantics, or did reference counted pointer macros

0

u/[deleted] May 27 '20

I actually don't talk about the technical merits of either language nor do I say that anything about the faults of C++ coming from C. As to your points. IDGAF about C. I like C++. I really don't think about C at all, so I'm not inclined to talk or argue with you about it.

P.S. This is response is a great example of a typical masochist critique of C++.

2

u/Veedrac May 27 '20

nor do I say that anything about the faults of C++ coming from C

Then I misread, sorry, not sure how else ‘Philosophically, this is more to like if python was implemented on top of PHP.’ was meant to be interpreted.

1

u/[deleted] May 27 '20

I was just using them as examples of hysterical and psychopathic languages. I was trying to make the shift In mindset clear. PHP is widely considered hacky but the people that use it care mostly about how effectively it helps them get things done. Python is very much about getting ideas fully formed from the mind into code. I understand why many programmers think about php negatively but its not so bad these days and I'm not so negative towards it.

1

u/Berkyjay May 28 '20

Woof, that's some fire being throw right there.

16

u/KingofGamesYami May 27 '20

C++ is not the only language that is regularly shit on by developers. JavaScript is another example.

What do these languages have in common?

  • They are or were widely used in industry

  • They provide many ways to write bad code.

9

u/lead999x May 27 '20 edited May 28 '20

It's important to note that they have the second problem for very different reasons.

For C++ it's because the committee has literally tacked on every programming language feature they've ever heard of leading to the language becoming incoherent. There's a difference between having a language be unopinionated and having it try to include everything and having every codebase and every programmer's knowledge be inconsistent. Dr. Stroustrup himself has written that there is a smaller, cleaner language inside of C++ waiting to get out or something similar. Frankly it just needs to be replaced by a leaner language that provides just some basic abstractions over C. If D hadn't failed due to its mandatory garbage collector, it could've been that language.

On the JavaScript side I think the problem lies heavily in automatic type conversions not always behaving as would be expected as well as equivalence not behaving as expected. The simple solution there is just to make all type conversions explicit(i.e. by typecasting) and not trying to compare unlike types. In any case, JavaScript may as well be a case study in how not to design a dynamic type system. And its heavy usage in industry was only because until relatively recently there was no alternative.

10

u/JNelson_ May 27 '20

It's crazy the range of programming style you can have with C++. You can be in a file one minute and looks basically like it's C99 with overloading. Then you come across some polymorphic mess with virtual functions coming out the wazzoo and auto's everywhere. When there is such a wide range of styles people are going to hate it for exactly that reason.

7

u/lead999x May 28 '20

That and the attempts to add closures and std::function and trying to be object oriented, and functional, and procedural and work at high at low levels of abstraction all at once. And the other thing is, it's fine to have those features if they're presented in a consistent manner but no C++ has to make 5 things that are radically different all have weirdly similar syntax so that:

  1. You can't remember all the features and there's no intuitive way to figure them out from what you do remember.

  2. If you type something even slightly wrong the compiler may give you an incorrect error because it assumes you're trying to do something other than what you actually are. (I'll admit compilers have gotten a lot better of late. Shout-out to Clang++.)

But other than its inconsistency, I like C++. For someone who knows how to use it, it gives you the power to do whatever you want however you want to. It was my first real programming language and the one I know best at this point. It will always hold a special place in my heart.

1

u/[deleted] Jun 03 '20

While programming in c++ you need to constantly remind yourself of which features you've implicitly banned by settling in on your style, its weirdly mentally taxing in a way.

1

u/JNelson_ Jun 03 '20

I often just match the style of the code I am writing in. Reading legacy code it's quite jarring and confusing if you come across and someone has suddenly started using classes or whatever or has gone out of their way to avoid using a macro when actually it was just as simple to use the macro.

1

u/Mad_Jack18 May 28 '20

Also PHP too

14

u/CoffeeTableEspresso May 27 '20

First of all, some context for those quotes.

The Torvalds quote is like 20 years old, when C++ was a much worse language than it is now. Torvalds has even softened towards C++ in recent years. I doubt he'd say something like that today.

Jonathan Blow is frankly talking out of his ass. C++ is the industry standard for game development for a reason. And he has no metrics at all to back up his claim. In fact, his language isn't even publicly available yet.

However, C++ is a weird mess. It's a massive language, backwards compatible with C for the most part, and with older versions of itself. For this reason you see lots of weird edge cases and duplication of features that you don't have in other languages.

Some of the complexity of C++ is unavoidable though. Things like having no garbage collector. For the domains that use C++, where things being performat and real-time are important, a garbage collector is a non-starter. So you basically have to deal with the memory yourself, which seems like added complexity to people not working in those kinds of domains.

A lot of people also don't learn C++ very well, and end up hating it because of this. For example, in the C++ class I used to TA, the profs would tell kids to just use new and delete everywhere, when in reality you should be stack-allocating most stuff. So the kids are getting all these errors about invalid pointers when they shouldn't have even been dealing with pointers in the first.

Also, I'd take things your profs say with a grain of salt. They likely haven't coded in 10+ years at least, and professors generally aren't very pragmatic people. There's a reason why C++ is very widespread despite all its flaws.

9

u/[deleted] May 28 '20

[removed] — view removed comment

1

u/CoffeeTableEspresso May 28 '20

You can still get memory problems with cycles, but I agree.

For a lot of people though, it's just not a problem. GC does what they need.

And yes, I do think a lot of people who criticize C++ aren't too familiar with C++. (Not that theres nothing to criticize with C++, just most people who don't use it criticize it for the wrong reasons.)

3

u/hugthemachines May 27 '20

I think it is a combination of having plenty of options, so the code can look very odd if the coder have gone a very different path compared to what you would have chosen. They make it backward compatible so lots of old code lines can look very different from the modern code style, using the modern features. The language is very large, that makes it hard to learn all of it. Compared to something like Golang where you can learn all the keywords and stuff very quickly, because it is one of their focus areas.

C++ is fairly old, and of course someone who makes a new programming language feels like they "do everything right from the start" but get a huge industry coverage and run with it for 40 years and then we can see how it performs.

Now, there is something to say about the language bashing in the world. All much used languages have some people who are upset about the problems of the language, and all programming languages has some problems. So there is no point in looking for a problem free one. Also every tool is not right for every job.

5

u/AbyssalRemark May 27 '20

I personally love C++. Its the power of C with the addition of object oriented code (and templates functions. I love templates functions). However.. it can be a mess.

A big part is how C++ was trying to be an extension of C. That kinda make things get confusing as they were trying to avoid making new keywords to allow C code to compile as C++ code. Because there is SO much C code.

C# (to my understanding) was trying to redo C++ without that backwards comparability, and in theory has less of this confusion but I cant speak to it as I havnt done C# much.

Dlang looks promising though. Trying to be the next iteration. But I have not looked into it enough to recomend it. But it has potential.

11

u/lead999x May 27 '20

C# (to my understanding) was trying to redo C++ without that backwards comparability, and in theory has less of this confusion but I cant speak to it as I havnt done C# much.

Nope, C# is Microsoft's Java.

Dlang looks promising though. Trying to be the next iteration. But I have not looked into it enough to recomend it. But it has potential.

D has been around a long time and failed to gain any significant adoption because of its GC issues and lack of any particular advantages to recommend it over the much better known and battle tested C++.

On the other hand Rust is gaining ground but even it has a long ways to go before it catches up to C++ and frankly Rust may suffer the same problem as C++ if it tries to add far too many language features over time.

5

u/CoffeeTableEspresso May 27 '20

I would love if D were used more often. It's like, C++ but designed coherently from scratch (and without C back-compat).

Sadly, C++ is just too entrenched to be replaced by a language that's "same but done better".

5

u/lead999x May 27 '20 edited May 27 '20

D also had major problems where its standard library didn't work without the GC, making it nearly impossible to use in cases where GC use was unacceptable. And on top of that its GC implementation was less than stellar.

2

u/[deleted] May 28 '20

Also they lack a respectable containers module for really doing anything useful. They'd argue you can hand roll things 'easily', but to be honest, they really should have more than just linked lists and arrays at this point.

4

u/lead999x May 28 '20

That's true. C++ users in particular are used to having a wide variety of standard library data structures available. And they're not wrong that anyone who ever took a basic data structures class or read a book on them can write arrays, vectors, stacks, queues, dequeues, hash tables, etc. but their implementations will probably not be very performant or even well-formed compared to those made and tested by professional programming language implementors. Even C has battle tested third party libraries for many basic structures.

1

u/AbyssalRemark May 27 '20

So D needs work. But C++ isnt going to change any time soon.

6

u/lead999x May 28 '20

C++ changes with every version and it's committee has progressively tacked on every language feature they have ever heard of. And D has been around for a while now, we haven't seen the developers working to address the major problems the community has identified with the language. I don't have high hopes for it. Rust and Nim seem to be targeted at the same application domains and they're doing much better, especially Rust.

2

u/[deleted] May 27 '20

Honestly, with every language you’re going to find a subset of people who hate it. No language is perfect and there’s always going to be that one thing that you find that works perfectly in one language that is absolute dog shit in another. That’s why some languages are better suited for your use case than others. For example, you need something for high performance computing, JavaScript is probably not the way to go, but that doesn’t make JavaScript a “bad language”.

Don’t get me wrong, I’m not saying that languages aren’t deserving of criticism or hate, it’s just that you should take most of it with a grain of salt mainly because in order to have an opinion about one language, you’d probably need to have worked with a few of them and when you get so used to the way one language works it can be annoying to learn a new one.

I learned Java in school, but for my job I mainly use C#. These are basically the same when you get down to semantics and paradigms, but there are some basic things in C# that are really a pain in the ass to work with that are easy in Java and vice versa. That’s just the way it works sometimes.

2

u/OmegaNaughtEquals1 May 27 '20

I think Bjarne said it perfectly:

There are only two kinds of languages: the ones people complain about and the ones nobody uses.

2

u/[deleted] May 28 '20

For me the only annoying part of C++ is header files. And the Windows API feels the need to #define the same data types 50 times for 'different usages'.

4

u/gvargh May 27 '20

~probably~ because they're triggered that their blub languages can't compete.

especially C programmers. when you see C++ offering memory-safe smart pointers for memory management, zero-cost coroutines instead of error-prone state machines, and safe and efficient views for arrays and strings, you're gonna get a little salty

1

u/headhuntermomo May 28 '20

To older C programmers like me C and C++ are the same. C++ just throws a bunch of stuff that you don't have to use on top. C++ doesnt force you to use objects. It doesn't force you to do anything. It isn't that hard to write C++ code that also compiles as C. In fact I try to do that if I can because a C source file has better compatibility with other languages. It is easier to call from Rust or Lua or Python if you need to. That is one downside to objects and templates.

2

u/grpagrati May 27 '20

I like C. It's lean, straight forward and simple. I hate C++ because it adds a whole cataclysm of unneeded complication just to make things "object oriented". I tried it (still do when I have to), but went back to C and if there's no specific reason, I ain't budging from here

1

u/JNelson_ May 27 '20

You can't deny object oriented programming has it's uses? Constructors and destructors are amazing to have. There is nothing worse than coming across C code written with 3 different implementations of constructors and destructors for a struct type. I think C is a good language but C++ just adds lovely things like classes, constructors, destructors, overloading, operator overloading, namepsaces. I do agree C++ can get bloated and confusing but it depends on the programmer writing now the language.

1

u/feelings_arent_facts May 27 '20

From my understanding, it's because it's packed with tons of features that, without a decent development style guide, can get you in a lot of trouble.

Similarly, it's usually compared to Java which runs on a VM which is much safer for a beginner to dabble in.

However, *most* enterprise code that is worth a damn is written in C++.

1

u/_souphanousinphone_ May 28 '20

If you use modern C++, it's actually pretty nice. It's a big investment to learn, but it's worth it. However, I will say that I really hate the build system. Even modern CMake is such a fucking mess when you compare it to other languages. I'm rooting for the other competing build systems to continue to get better.

1

u/[deleted] May 28 '20

Let’s see... who designs the hardware???

1

u/OnlySeesLastSentence May 28 '20

Because it doesn't have the beauty of C and doesn't have the simplicity of python.

1

u/guepier May 28 '20

Funny, many people would phrase it exactly the opposite way: it doesn’t have the simplicity of C or the beauty of Python.

1

u/OnlySeesLastSentence May 28 '20

That's odd. Python is one of the simplest languages I've ever seen. And C just looks pretty compared to other languages lol. Aggravating as fuck, but nice and neat.

1

u/BenRayfield May 28 '20 edited May 28 '20

Cuz you can't know what code will do before running it unless you are very careful to avoid the buggy nonstandardized parts and cuz eventually you will need a library where they weren't so careful so it's a minefield and you will step on the mines or someone will make you. Imagine finding a huge open area with a sign that says warning minefield here are some known safe paths which can compute every possible thing (higher level languages). Only a fool explores a minefield after hearing some of his friends made it across. So what? If you keep walking randomly around it will happen. There's only 1 reason to ever use C++ and that is to trade reliability for efficiency of doing the exact same thing. Even if you have to generate assembly opcodes using JavaScript, at least you know for sure it will work.

1

u/JohnMcPineapple May 28 '20 edited Oct 08 '24

...

1

u/ljgwwbg Jun 25 '20

My 2c

If c/c++ were so bad why there is always some comparison against them? Why noone compares against awk? Or forth? Or prolog? Or smalltalk? Or, God forbid, cobol.

Why some cannot take them for what they are?

C/c++ are just fine for what they are. If you do not like them use es, ts, c#, rust or elixir or swift or whatever clicks with your mind.

Barking at language that 40 or 50 years around doing fine things is, IMHO, barking at the wrong tree.

Or better question may be: why we do not try to make something today that will work for next 100 years? Some IBM programs can be run 50 years later with no modification. Can we beat that?

Do not worry, next os update will just break it all

1

u/AdmiralAdama99 May 28 '20

Not an expert, but my guess is C++ is controversial because it's a lower level language. C++ code is closer (in terms of its data structures, keywords, etc.) to how a computer operates than higher level languages.

Low level languages require more work on the part of the programmer than higher level languages to get things working.

Of course, there can be good reasons to use a lower level language. Performance, access to memory management, etc. But there are also plenty of reasons to save yourself some headache and use a higher level language.

-1

u/aelytra May 27 '20

I too, avoid C++ like the plague. I do know C++, have used it for more than just a few trivial projects, and used it daily for several months.... but I go out of my way to avoid it wherever I can, because:

  • There's a lot of hand holdin' w/ the compiler

  • Undefined behavior :(

  • I like garbage collectors.

  • I like not having to manage include files or having to redefine function/method signatures.

  • I can do the same stuff with less effort on my part... in other languages.

I'd also agree with Linus on the "It's made more horrible by the fact that a lot of substandard programmers use it". The sheer number of ways you have available to shoot yourself in the foot with the language (because, memory management is hard.), makes for a lot of worries about steppin' on a landmine.

I don't have to worry nearly as much in VB6, C#, or Java. Stuff just kinda works like you'd expect in those worlds.

3

u/odd__nerd May 27 '20

There's a lot of hand holdin' w/ the compiler

Use a build system.

Undefined behavior :(

Write code according to the standard and use static analyzers (specifically the undefined behaviour sanitizer) to prevent troublesome code.

I like garbage collectors.

Use RAII. If you feel like you're manually managing memory you're doing it wrong.

I like not having to manage include files or having to redefine function/method signatures.

This is a matter of opinion and many (including myself) prefer the separation of an API from the implementing code even if that breaks DRY. Nevertheless, modules (albeit they just came out) allow you to write it all in one place.

I can do the same stuff with less effort on my part... in other languages.

This is just implying C++ is not the correct language for your problems. No one should use any language to solve a particular problem without thought or they'll run into the same issue.

2

u/balefrost May 27 '20

Undefined behavior :(

Write code according to the standard and use static analyzers (specifically the undefined behaviour sanitizer) to prevent troublesome code.

Surely the reason that undefined behavior exists in the spec at all is that it's not always possible to detect statically. If it could be detected, why wouldn't the compiler emit an error? Sure, UB might be statically detectable in some cases, and can maybe be uncovered via instrumenting the running application, but it can't be correctly detected in all cases. So it's something that you do always have to keep in mind, even with the best tools.

2

u/odd__nerd May 27 '20

You are absolutely correct, some of the guarantees C++ wants to offer impose some undetectable errors hence the compiler answers wrong to "is this a program?". However, I carefully said "to prevent troublesome code" because UB tends to be difficult to produce if good code is written. Obviously that doesn't always work, but by allowing tools to tidy code and state when something should be avoided not because it's wrong but because it can be done so much better and safer, the pitfalls of the language are no longer unmarked traps and become relatively simple to avoid.

1

u/CoffeeTableEspresso May 27 '20

Things like valgrind though, will catch a lot of problems for you...

1

u/aelytra May 27 '20

> There's a lot of hand holdin' w/ the compiler

Use a build system.

I meant with the quantity of boilerplate w.r.t declaring a function or prototype, plus the overall verboseness (not to mention const correctness..). When I do use C++, I do use a build system like MSBuild or a makefile (depends on my goal.)

I'm gonna pick on https://github.com/OpenZWave/open-zwave/blob/master/cpp/src/Scene.cpp for example.

for (vector<SceneStorage*>::iterator vt = s_scenes[i]->m_values.begin(); vt != s_scenes[i]->m_values.end(); ++vt) 

would've been more preferable to me as: foreach (var value in scene.values) { }. And shouldn't that iterator be a const_iterator too, since the collection's not modified? Soo much to think about.

snprintf(str, sizeof(str), "%d", (*vt)->m_id.GetNodeId());
valueElement->SetAttribute("nodeId", str);

would've been more preferable to me as: valueElement.SetAttribute("nodeId", value.NodeId). This way I don't have to worry about how big my buffer is, how/where it's allocated, how many times I dereference a pointer, how many times I implicitly call a copy/move constructor, etc. (I do get that you can just refactor everything so that I can write code in C++ that looks exactly like that.)

Write code according to the standard and use static analyzers (specifically the undefined behaviour sanitizer) to prevent troublesome code.

That's what I do. -WAll and warnings are errors are my preferred settings when working with C++.

Use RAII.

I do. But all it takes is for one person to not to... and you end up with use-after-free bugs or even memory leaks. Everyone's gotta agree on who/what owns what chunk of memory and how/when it's freed, how/when to transfer that ownership over the memory, etc. It's just a bit overwhelming to think about it all the time.

many (including myself) prefer the separation of an API from the implementing code

Me too! Interfaces make unit testing easier.

Nevertheless, modules (albeit they just came out) allow you to write it all in one place.

I'll look into that. Thanks for the tip.

edit: Looked into it. It's pretty similar to typescript's export/import stuff. I'll use em' next time I write C++.

This is just implying C++ is not the correct language for your problems.

And you're right - most of the time C++ really isn't the solution for the types of products I develop.

2

u/Astarothsito May 27 '20

I do get that you can just refactor everything so that I can write code in C++ that looks exactly like that.

..., so C++ provides you all the tools to make your code the same way you want, but you don't want to use them..., how C++ is going to help you with that? (If this is ancient code that doesn't fails, why change it anyways?)

for (vector<SceneStorage*>::iterator vt = s_scenes[i]->m_values.begin(); vt != s_scenes[i]->m_values.end(); ++vt)

for(auto vt : s_scenes[i])

snprintf(str, sizeof(str), "%d", (*vt)->m_id.GetNodeId()); valueElement->SetAttribute("nodeId", str);

valueElement->SetAttribute("nodeId", to_string(vt->m_id.GetNodeId());

The only thing is that it wouldn't care about that code, is already written, and is before could get auto and to_string... and if you have the option why don't pass 'SetAttribute' the integer when building your XML.

1

u/odd__nerd May 27 '20 edited May 27 '20

I meant with the quantity of boilerplate w.r.t declaring a function or prototype

Yeah, the language has all the wrong defaults but they're trying to change that (hopefully in C++23 if everything goes correctly).

foreach (var value in scene.values) { }

For a decade now in C++ this would be for (auto value : scene.values) or std::for_each(begin, end, lambda) depending on what is needed. C++20 also standardized ranges which will clean up a lot of iterative code that needs to do something more complex like filtering.

valueElement.SetAttribute("nodeId", value.NodeId)

Formatting has been a major issue in the language, no way to get around that. However, C++20 standardized fmt which solves the problem. For that particular example though std::to_string or even just a cast operator would be sufficient, no large scale refactor required or even new libraries.

-WAll and warnings are errors

Yes but specifically the clang tooling is what I was referring to. A lot of static analysis tools in the ecosystem work alongside one another instead of replacing each other which (for better or worse) better follows the Unix philosophy.

But all it takes is for one person to not to

I personally do not run into this problem often. If a library is needed which uses C ownership semantics then wrappers should be put around it to handle the boundaries. Clang-tidy can also fix some of the simple uses of raw pointers too and the memory/address sanitizers are great at finding memory leaks and use after frees meaning those problems are found immediately. Not an ideal solution, but ideally code written for the current version of the language would be used instead so those problems didn't exist.

1

u/furbyhater May 27 '20

for (vector<SceneStorage*>::iterator vt = s_scenes[i]->m_values.begin(); vt != s_scenes[i]->m_values.end(); ++vt)

would've been more preferable to me as: foreach (var value in scene.values) { }.

In C++11, it's just for (const auto v : s_scenes[i]->m_values), so strawman.

1

u/aelytra May 27 '20

yeah, I've got a bunch of syntax to catch up to. I left the language altogether cause C++03 was terrible.

1

u/JNelson_ May 27 '20

Just use macros and turn it into javascript.

1

u/guepier May 28 '20

This is a matter of opinion

Not really. Or at least, virtually all C++ experts and the C++ committee agree with the comment you’re replying to here: header files are bad and there’s active work underway to finally replace them with something more modern.

You can achieve separation of API without header files.

1

u/odd__nerd May 28 '20

Header files are bad, that's why modules exist, but they intentionally don't require everything to be in one place. The cited problem above was the need to repeat function signatures in both a header and a translation unit whilst keeping them the same, not simply the vast problems with headers. One can still repeat this separation without all the problems of headers when using modules because the committee does not see that separation as a problem, but rather headers were a poor way to offer it. If headers suck is not an opinion, they do, but if an API should be repeated separate to the implementation is hence the version of modules accepted into the standard.

2

u/guepier May 28 '20

The cited problem above was the need to repeat function signatures in both a header and a translation unit whilst keeping them the same

OK, I read that differently: i.e. that you either have to include a header file “or … redefine function/method signatures”. But you may be right, and in that case I agree with you that having a separation of interface and implementation is superior to what most languages offer.

3

u/AvidCoco May 27 '20

You lost me at "I like garbage collectors".

Try doing anything with real-time constraints with a garbage collector and you'll soon learn to despise them as you should.

5

u/hugthemachines May 27 '20

So you are saying you dislike using screwdrivers as hammers? That is pretty normal.

So your own specific context may not apply to the job they do. If that means they lost you, that means you are only looking at the world through a very small scope. Programming languages without GC are not the best for every programming job.

1

u/teriyaki7755 May 27 '20

Language is a tool wrong tool for any job is bound to end up as failure

4

u/teriyaki7755 May 27 '20

This problem they faced with Go in discord app where they found that the garbage collector hogged resources like crazy hence they had to rewrite certain things with rust.

4

u/TGR44 May 27 '20 edited May 27 '20

Most applications don’t have “hard” real time constraints.

If you do (e.g. you’re writing a kernel) then, yeah, throw away anything with a GC (though note that automatic Reference Counting — which is acceptable in some cases with real-time constraints — is sometimes also referred to as “GC” and that some GC implementations are “pauseless”).

However, even many things where you’d expect latency to be critical such as telecoms can make do with “soft” real-time. Examples include MetaSwitch Rhino Telephony Application Server and [anything written in Erlang](https://en.wikipedia.org/wiki/Erlang_(programming_language)

Basically, use the right tool for the job: Don’t write the firmware for a pacemaker in Python it’s mostly reference-counted but definitely isn’t deterministic and don’t write your REST API in C.

1

u/CyborgPurge May 28 '20

However, even many things where you’d expect latency to be critical such as telecoms can make do with “soft” real-time.

Hell, you can write IVRs with Rails and it be plenty performant depending on volume.

1

u/aelytra May 27 '20 edited May 27 '20

I have actually; just not the hard real time constraints typical of embedded platforms that control vehicles.

Basically, use mutable data structures and don't call new(). No memory allocations = no trash to collect. C# even has nifty keywords like stackalloc.

1

u/CoffeeTableEspresso May 27 '20

So you're using a garbage collected language, then ... refusing to do anything that would have to be garbage collected...

2

u/aelytra May 27 '20

Yep, or at least minimizing the memory allocation rate as much as possible so that when a collection does occur, it doesn't pause the app for very long. (e.g. things like not calling new byte[65536] in a loop to just discard it afterwards... just reuse it.)

The desktop operating systems I work with daily all do pre-emptive scheduling anyway, so a 16ms pause is no different than the OS scheduling a different thread to run for a bit.

Bonus points if the allocation rate is so low that the O.S. is able to free it all at once for you when your app terminates.

1

u/CoffeeTableEspresso May 27 '20

At that point I'd just prefer to use C++ honestly. I've seen Java in the style you describe and it's never idiomatic and always worse than the C++ it's trying to avoid IMHO

1

u/aelytra May 27 '20

Agreed. C# is in the process of making changes to the language to allow you to be more expressive with how memory is allocated, with the introduction of "ref structs" & "stackalloc" - basically forcing your objects to live on the stack only. It's useful for certain types of code (like turning a byte array into an object).

My usual architecture for near real-time services goes like this:

  • program starts up. instantiates everything it needs for the lifetime of the app.

  • program's running - can still allocate small objects, but they're going to live for a super small amount of time. GC's do happen, but it pauses for a super tiny amount of time; it's just allocating a fresh chunk of memory and discarding nearly the entirety of the old chunk (the only things referenced are references on the call stack). It's a bit faster to discard a giant chunk of memory all at once than it is to discard teeny tiny chunks much more frequently.

  • program exits - release all the external resources, and let the O.S. free all the memory pages at once.

That architecture that uses object pooling and abandons the new operator altogether? I hate it. It's ugly. If you truly need zero pauses over the course of months, that's how you do it. But I live in a pre-emptive multitasking world and my app's gonna get paused anyway, so I put up with the tiny pauses so I can keep my sanity.

1

u/headhuntermomo May 28 '20

You like BASIC better than C++? Sigh.

0

u/teriyaki7755 May 27 '20

"Too many know it very few implement it correctly and then complain about it. Also it didn't really had a standard until recently considering its an old language. Poor implementation means slower execution compared to other languages." I am using it from high school and am about to graduate with it using it is really difficult compared to some other languages but I still understand my data structures best when I explain them using pointers in C or C++. Also, it is taught poorly in schools. To someone new to programming don't even bother touching C++ ever you won't regret it.

1

u/CoffeeTableEspresso May 27 '20

It has been standardized since 1998, I'd hardly call that "until recently".

And regarding performance, C++ outperforms pretty much every other language out there.

0

u/CptBread May 27 '20

I'd change "outperforms" with "outperforms or are on par with".

2

u/CoffeeTableEspresso May 27 '20

I mean, off the top of my head, C, Rust, D, Fortran, are roughly on par with C++ in terms of performance, which I why I said "pretty much every". (Maybe I missed a few but hopefully you get my point.)

Pretty much everything else is going to be noticeably slower than C++ except in very specialized circumstances.

2

u/[deleted] May 27 '20 edited May 27 '20

[removed] — view removed comment

1

u/aelytra May 27 '20

Outta curiosity, how do you express ownership of an object in C++?

FWIW, the other languages I know (C#, Java, VB.NET, TypeScript/JavaScript) pass copies of objects around by copying the ~4 byte reference to the object and not the actual object itself. Similar to C++'s ampersands.

1

u/guepier May 28 '20

how do you express ownership of an object in C++?

You seem to have not gotten a reply so far so let me answer this question, because it’s crucial to understanding C++.

“Ownership” of a resource is defined by whoever releases the resource. A “resource”, in turn, is anything that needs to be “released”: memory, file handles, database connections, … but you can also express quite different things as resources: for example, commands that require sending a “commit” at the end. C++ (and some other languages) make it convenient to think of all these things as resources.

Furthermore, C++ makes it easy to tie all these resources to the lifetime of an object, so that a resource is released when the object’s destructor is called. This now means that “ownership” in C++ is defined as object ownership: who calls the constructor?

For most objects this is (or at least was) straightforward: automatic object storage means that all non-pointer objects are owned by the local scope. At the end of the scope, object lifetime ends and the object’s destructor gets called automatically — no matter how the scope was left (i.e. even when an exception was thrown). This is so powerful that it got its own name, RAII. (I’ll omit move semantics here for brevity.)

For pointers, ownership gets more complicated because now multiple pointers can point to the same object, which may not have automatic storage (because it was allocated on the heap, e.g. via new). Since the object’s storage is not automatic, something needs to manually deallocate it and (thus) trigger the destructor. But who? Who owns the resource behind the pointers? When using raw pointers, this is not obvious, and requires careful tracking by the programmers.

C++ therefore introduced several types to express the ownership semantics of pointers, via so-called “smart” pointers. The concept isn’t new, but since C++11 the concept got better support by the standard via two types: unique_ptr, to express that a resource has one unique owner, and shared_ptr, to express that a resource is truly “shared”: each owner (= pointer) tracks that they are still “alive”, and the last “live” owner is in charge of deleting the object once they die.

By contrast, a unique_ptr is conceptually much simpler: it does not allow anybody else to own the pointee object (= the object being pointed to). It allows access to its pointee, but that access needs to happen while the owner is still alive. There is only one exception: the ownership can be passed on to a successor before the original owner “dies” (via move semantics, alluded to above). Even though unique ownership sounds very restrictive and requires careful thought about the semantics, it is actually sufficient in most situations (almost all resources turn out to have one logical owner), and permits writing very simple, efficient code.

There’s a lot more to ownership but the above is enough for 99% of cases, and most C++ programmers never need to learn more.

1

u/aelytra May 28 '20

Neat. Sounds a lot like what I do in C# w/ dependency injection containers.

Back when I actually learned and used a ton of C++ and grew to loathe the language.. it was C++03 that was in use and C++0x was being drafted. After that, every time I looked at some open source project's code, it kept on using the C++03 style code that I hated so I never found out about the newer language features like 'auto'.

1

u/guepier May 28 '20

DI is different. If you wanted to be cynical you could say that “DI” is just a fancy term for “argument passing”.

The most direct equivalent of a resource in C# is something that implements IDisposable.

2

u/[deleted] May 27 '20 edited May 27 '20

[removed] — view removed comment

1

u/aelytra May 27 '20

It appears C++'s gotten a lot more syntactic sugar since I last used it seriously (when C++03 was a thing and C++0x was being drafted). That sugar makes it a much nicer language to me.

So ownership's defined mainly by who called the constructor for the object, and all it takes is not putting a & when passing the object around.. and suddenly you're the new owner?

1

u/furbyhater May 27 '20

Not really, for heap-allocated objects ownership is usually defined by who constructed the std::unique_ptr that holds the object, and you pass it around using std::move. For shared ownership there's std::shared_ptr.

If you pass it around by value (without &), you'll just make a copy of it. Of crouse it all depends on how your copy-constructor is implemented.

1

u/JNelson_ May 27 '20

The code base I work with is more like C than C++ so I mainly work with raw pointers. I've got so used to it now I don't think to use unique or shared pointers. Is there any specific advantage to these other than ensuring the underlying heap memory is freed when the pointer goes out of scope?

2

u/[deleted] May 27 '20

[removed] — view removed comment

2

u/aelytra May 27 '20

Well good sir, you have just convinced me to put C++ back into my toolbox.

C++03 was the reason I hated the language so much.

2

u/SkoomaDentist May 28 '20

std::string was there since the beginning of the standard.