News for hackers. Stuff that matters.
Re:C++ by Example by arberx on Thursday September 22, 2022 @10:07AM (#32938930)
As my first language, I've yet to experience another language that genuinely lets me be as creative as C++.

There are hundreds of ways to implement and optimize similar functionality that I feel like an artist writing in it. This, of course, comes with many downsides.

Re:C++ by Example by Chabsff on Thursday September 22, 2022 @10:34AM (#32939323)
And this half of my main beef with the language. To be clear, I absolutely agree that this aspect of it is wonderful, but it is a double-edged sword, and the edge pointing at the programmer's face is very sharp.

The second half of that beef is that most C++ learning journeys bring the learner up to the point of creativity without addressing concepts like Strict Aliasing which are not useful until you start getting "creative". That's big a problem because code containing strict aliasing violations (and/or any of a myriad of other UB) is often fundamentally broken while giving the illusion of behaving as intended.

Re:C++ by Example by synergy20 on Thursday September 22, 2022 @10:42AM (#32939444)
or use -fno-strict-aliasing and profile the code to lift it for bottleneck code carefully? linux kernel does not allow strict-aliasing for example. but I agree yes all c and c++ course should teach strict aliasing.

in modern c++, also teach RAII and unique_ptr, combined they can eliminate so many memory safety problems.

Re:C++ by Example by Chabsff on Thursday September 22, 2022 @10:57AM (#32939720)
C++ without strict aliasing is not C++ anymore. Furthermore, that was just an example. There are other such concepts, such as the illegality of accessing memory as anything else than raw bytes or the type of the object that resides there (which also applies to union fields). Another one would be the fact that signed integer overflow is UB.

C++ is so tightly bound to memory layouts that once you start getting a solid mental model of what's going on, it's really easy to come up with legitimately neat and creative ideas that work very well and fast on a test bench environment without any complaint from modern compilers, but are fundamentally broken. I feel we do not do a good job at equipping up-and-coming programmers so that they can benefit from that mental model without writing code that only works out of sheer luck.

In the extreme, you can write code that does stuff like dynamically retype an object by swapping out its vtable when vtables are not even thing as far as the language is concerned. It's astounding what it sometimes feels like you are capable of doing in C++.

Re:C++ by Example by kazinator on Thursday September 22, 2022 @01:58PM (#32942418)
> C++ without strict aliasing is not C++ anymore

That is completely false.

Firstly, a C++ implementation that doesn't optimize based on no aliasing assumptions can be entirely conforming: it can handle all correct, portable programs in the required way.

Secondly, the handling for programs which do type punning doesn't make it not C++ anymore; just a dialect. Programs in that dialect are C++, just not ISO C++.

Every implementation of a standardized language is a dialect of that language; the standard just explains what is the common dialect (theoretically) supported by all of them.

In fact it's common for C and C++ compilers to recognize their own dialect by default.

Re:C++ by Example by arcticbull on Thursday September 22, 2022 @04:05PM (#32943945)
> That is completely false.

I suppose but only because C++ is everything and nothing. C++ compilers are borderline self aware because the spec is 'write literally whatever you want'. Skynet was obviously a C++ compiler ;)

Re:C++ by Example by kazinator on Thursday September 22, 2022 @06:10PM (#32945280)
The meaning of punning memory is obvious if you understand the implementation-specific representations being used. E.g. if you understand what a 64 bit double looks like and what a 64 bit integer looks like, then it makes sense when you look at the memory of one through the type of the other. The C or C++ program to it has only two rationally defensible meanings: "undefined behavior" (ISO C or C++ interpretation, allowing certain optimizations, or run-time diagnosis of a type mismatch or whatever) or else "do the obvious thing and access the bits like the code says". What the code is asking for can certainly be be framed in terms of concepts in the standard. Just what the code is obviously requesting is not granted by any requirements in the standard. The idea that by asking for it, it's not a C++ program any more is silly.

There is no standardized programming language that doesn't have vendor specific extensions comprising a local dialect.

Re:C++ by Example by stoeckley on Thursday September 22, 2022 @01:49PM (#32942302)
I remember once telling a friend of mine, after I'd spent several years writing Clojure full-time, that upon getting back into writing C++, the feeling was like "sculpting with electricity." There is a strange sense of power you feel from harnessing the language in a creative way, unlike any other language I've used.
Re:C++ by Example by kazinator on Thursday September 22, 2022 @01:59PM (#32942427)
Did he mean with rubber gloves and insulated mat, or without?
Re:C++ by Example by synergy20 on Thursday September 22, 2022 @12:46PM (#32941430)
I understand compiler likes strict aliasing for performance optimizations, use it carefully but _only_ at bottleneck-ed areas seems like a good trade-off between safety and performance, why without-it is no c++ anymore? why do I need do pointer aliasing randomly?
Re:C++ by Example by Chabsff on Thursday September 22, 2022 @01:50PM (#32942323)
Strict aliasing is what prevents compilers from having to sprinkle Load-Hit-Stores all over the place. This is not a marginal performance difference, and doubly-so for CPUs with deep execution pipelines. It also has massive code-reordering implications.

In any case, Strict Aliasing is not a flippant rule that compilers like to apply. It's a formal component of the ISO standard that C++ is.

You can chose to make a deal with a compiler (via a flag) to compile otherwise non-compliant code in a consistent way, but that does not change the fact that the code is non-compliant.

Re:C++ by Example by kazinator on Thursday September 22, 2022 @02:32PM (#32942824)
There are ways of coding coding in C which makes those optimizations unnecessary.

The basic idea is: don't load your block of code with lots of pointer dereferences. Load the values you need into local variables. Don't proliferate common expressions which dereference the same pointer to get at the same value. Consolidate the assignments through pointers. Don't do this in three places: (*ptr)++. Have that value in a local variable var, and do var++ in three places, then assign it *ptr = var.

Even without no-strict aliasing, a compiler can still assume that local variables whose addresses are not taken are not the targets of any pointers.

In C (99 or later), you have restrict also. restrict is independent of strict aliasing, because it's not based on type.

Furthermore, speaking of restrict, aliasing between like typed objects matters for optimization. It's good and well to optimize based on the idea that a double * cannot be aiming at an object whose declared type is long. But it's insufficient, because code that is manipulating double * pointers is likely working with objects of type double which could be the targets of those pointers. So without some combination of tight coding and possibly using restrict, you will end up with those load-hit-stores in all sorts of code.

This code for removing from a linked list:

   node->prev->next = node->next;
   node->next->prev = node->prev;
still isn't as good as this:

   node *next = node->next;
   node *prev = node->prev;

   next->prev = prev;
   prev->next = next;
The problem is that the common expressions can't be eliminated based on aliasing, and the aliasing is between like types, so strict aliasing doesn't help.

With gcc (x86) I get:

        movl    (%eax), %edx
        movl    4(%eax), %ecx
        movl    %ecx, 4(%edx)
        movl    4(%eax), %eax
        movl    %eax, (%eax)
versus:

        movl    (%eax), %edx
        movl    4(%eax), %eax
        movl    %eax, 4(%edx)
        movl    %edx, (%eax)
We shaved off an instruction through tighter coding, and IMHO (in this case) improved the readability also.

That was gcc 7 on Ubuntu. The result is exactly the same like what I saw under gcc 2.7.x a quarter century ago.

How about gcc 11, x86-64? I should probably be using godbolt, but anyway, also five instructions down to four:

        movq    (%rdi), %rax
        movq    8(%rdi), %rdx
        movq    %rdx, 8(%rax)
        movq    8(%rdi), %rax
        movq    %rax, (%rax)
vs:

        movq    8(%rdi), %rax
        movq    (%rdi), %rdx
        movq    %rax, 8(%rdx)
        movq    %rdx, (%rax)

(I think in this particular case the compiler could do a better job because even if the assignment "node->prev->next = node->next" clobbers the value of "node->next" due to the nodes being aliases, the assignment can only clobber it with the value that node->next already has! The compiler doesn't analyze it that far though.)

C was designed from the start as a language which the programmer does the optimizing, and regardless of the advancements in compilers, that has not been entirely eliminated.

How you write C still makes a difference, even at the microscopic level of individual statements and expressions, not just the level of overall program organization and use of algorithms.

If you write tight code, you can turn off strict aliasing optimizations globally and it won't matter. But you don't have to do that globally. You may be able to confine your type punning hack in its own source file, and just turn it off for that file. (Or may be even on a finer granularity if you have such compiler support.)

Re:C++ by Example by rramadass on Thursday September 22, 2022 @12:35PM (#32941301)
Re:C++ by Example by Chabsff on Thursday September 22, 2022 @02:04PM (#32942497)
Just in case you posted this as a counterpoint to what I'm saying...

This blog effectively agrees with my position: Undefined Behavior is just "Stuff the compiler is allowed to assume never happens". And C++'s set of Undefined Behaviour is a fundamental part of what makes it valuable.

The issue I have is not with them, but rather with the fact that it's too easy to become competent, if not talented, way past the point where one should take them into account without having to even know of their existence.

Re:C++ by Example by rramadass on Friday September 23, 2022 @01:31PM (#32954783)
Re:C++ by Example by forgotpwd16 on Thursday September 22, 2022 @10:40AM (#32939410)
>There are hundreds of ways to implement and optimize similar functionality that I feel like an artist writing in it.

Perl? Can even write poetry in it. https://docstore.mik.ua/orelly/perl/prog3/ch27_02.htm

Re:C++ by Example by ncmncm on Thursday September 22, 2022 @11:05AM (#32939866)
"If new true friend not protected for explicit private union, break case and try using this."
Re:C++ by Example by bstamour on Thursday September 22, 2022 @04:05PM (#32943950)
... I think the perl code actually compiles (err, runs) though. :-)
Re:C++ by Example by avg_dev on Thursday September 22, 2022 @02:38PM (#32942892)
that is amazing
Re:C++ by Example by volsa_ on Thursday September 22, 2022 @10:51AM (#32939603)
As someone who tried learning C++ a few years ago this is (personally) my biggest gripe with the language and this gif[0] perfectly sums it up. Gave up and started learning Rust instead, which I'm very happy about in hindsight.

[0] https://twitter.com/timur_audio/status/1004017362381795329

Re:C++ by Example by ncmncm on Thursday September 22, 2022 @11:30AM (#32940290)
Fortunately, those can almost all be ignored almost all the time.

Rust will seem fine until you are writing a library and find no way to express what would make the library nicer to use; or you find using some library awkward and error-prone. Almost every C++ feature is designed to enable delivering more powerful libraries, and they compound.

So, in C++ you as library writer are empowered to make the use of your library correct by construction: what compiles is safe and correct. Rust makes the compiler responsible for memory safety, but offers much less to make using your library pleasant and foolproof.

Re:C++ by Example by oconnor663 on Thursday September 22, 2022 @01:50PM (#32942327)
I think Rust's combination of data-bearing enums and destructive move semantics goes a really long way towards letting library authors express their invariants through the type system. And that's in addition to the borrow checker and mutable aliasing rules. The mutable aliasing rules in particular are often kind of annoying for callers, but they're a godsend for API authors, because they allow for methods like Mutex::get_mut that don't even need to lock the Mutex, in safe code!
Re:C++ by Example by volsa_ on Thursday September 22, 2022 @12:01PM (#32940836)
> but offers much less to make using your library pleasant and foolproof

Not my experience so far, I might go as far and say it makes it more foolproof because when writing your library you have the option to return an `Option` or `Result` enum.

Re:C++ by Example by ncmncm on Thursday September 22, 2022 @12:25PM (#32941176)
Option and Result types are as easily coded in C++.

The former is in the Standard C++ library. The latter will be in the next, but anyway the one in Boost has worked fine forever.

Throwing, instead, is a choice unavailable to Rust coders, so you often have no alternative but to return these more complicated things that users are then obliged to unpack. A standard macro makes that easier, and is semantically equivalent to throwing, but imposes substantial overhead on successful calls.

Re:C++ by Example by mathstuf on Thursday September 22, 2022 @05:06PM (#32944631)
The fact that `std::optional<T&>` is verbotten makes them quite a bit more useless. The Boost one is better because it doesn't have this misguided limitation. It's really quite a sad story and a loss to all of C++ that it is this way (and not for lack of trying on ThePhD's part).

> no alternative but to return these more complicated things that users are then obliged to unpack

Yes, thank you. It is much better this way. I think "substantial overhead" needs to be backed up with some numbers here because setting up exception landing pads is certainly not free.

Re:C++ by Example by chlorion on Thursday September 22, 2022 @10:24PM (#32947264)
According to this link (posted below and includes benchmark results and a benchmark you can run), they compared result style error handling with conventional exceptions in C++, and the result style error handling (using an impl of std::expected) was "more than four times slower". According to the link and my understanding, exceptions are essentially "free" at runtime in the non-exceptional case on certain platforms such as Linux, but slower than result style error handling in the exceptional case.

I prefer result style error handling personally and I am not suggesting that it's worse or shouldn't be used, just thought the findings were interesting and worth considering.

https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p25...

Re:C++ by Example by mathstuf on Friday September 23, 2022 @10:55AM (#32952765)
So I did some testing with Rust and I don't think that the C++ "four times slower" applies to it at first glance. Maybe Rust can just do better optimizations or something because Rust knows that it is a discriminated union, but these kinds of conclusions can't just be ported across languages blindly.

Of course, porting the benchmark for `sqrt` wasn't trivial because (of course) C++ just modifies the span passed in making it easy to abstract out the allocations whereas Rust says "you cannot pass a mutable slice across a `catch_unwind` barrier", so all of my tests end up returning a new `Vec` inside the benchmarked function. I also wonder how much using an inner function for `fib` would allow some TCO to kick in and change results again.

In any case, I don't think that C++'s has anything that satisfies the use cases that Rust's `Option` or `Result` cover in its standard library, so even if `std::optional` and `std::expected` were magically faster, the fact that `std::optional<inner_field_type const&>` is not supported means I can't use it for what I want anyways and I'm back to Boost or hand-coding classes and dealing with corner cases myself. Which is, unfortunately, a C++-shaped problem that has existed for a long time anyways, so…nothing new.

Re:C++ by Example by chlorion on Friday September 23, 2022 @11:29PM (#32959505)
I agree that "four times slower" may not apply in Rust specifically.

I do think the idea that exceptions are faster at runtime (at least in micro benchmarks) can be ported across languages though just due to the way exceptions are implemented. In any language, a caller of a function that can return a Result or Option always need to branch to unwrap the returned value, but callers of functions that can throw don't have these branches at all (on platforms with "zero cost" exceptions). Whether or not it actually matters in practice is certainly debatable. I would guess that it will never be a real problem for most people.

Wrt to std::optional and std::expected, I also have found them to be pretty clunky and limited, especially compared to the Rust counterparts! The lack of pattern matching is one issue, the lack of optional references is another, and they just don't integrate with the language as well since most libraries and even std functions don't use them!

Re:C++ by Example by Rusky on Thursday September 22, 2022 @12:46PM (#32941433)
C++'s option and result types are much larger, uglier, and harder to use correctly than Rust's. The shift from throwing to returning a Result is not really an increase in complexity- closer to a reshuffling of syntax.

But that's not really all that relevant either, because comparing languages at this level of detail misses the forest for the trees. An interesting comparison takes a step back and compares which problems the languages (try to) solve. Often something that appears to be a clear win for one or the other turns out to be a non-issue.

Re:C++ by Example by arinlen on Thursday September 22, 2022 @05:13PM (#32944698)
> C++'s option and result types are much larger, uglier, and harder to use correctly than Rust's.

What's your rationale for claiming in a swiping generalization that implementing a data type, regardless of all options or approaches and design, has no other option than doing everything wrong?

Re:C++ by Example by Rusky on Thursday September 22, 2022 @05:25PM (#32944828)
I mean, have you looked at them?

C++'s standard library optional type is a tagged union implemented from scratch, with a dizzying array of template metaprogramming to meet the standard's requirements- see e.g. Microsoft's here: https://github.com/microsoft/STL/blob/main/stl/inc/optional#.... This isn't a criticism of the team behind this code, it's just what it takes to do this in C++.

Rust gets most of that functionality from the language instead, in a much cleaner way. Sum types are built in, value categories and move semantics are handled automatically, there is little-to-no metaprogramming, and most of the API is just simple convenience combinators with obvious implementations: https://github.com/rust-lang/rust/blob/master/library/core/s...

If nothing else, this is a clear counterexample to the claim that "Option and Result types are as easily coded in C++."

Re:C++ by Example by arinlen on Thursday September 22, 2022 @06:16PM (#32945343)
> I mean, have you looked at them?

Last time I looked at Rust's std::Result, it's implemented as a tagged union.

Most of C++'s implementations of a Result data type are implemented as tagged unions as well.

What's your point?

> This isn't a criticism of the team behind this code, it's just what it takes to do this in C++.

The only conceivable argument you can possibly make is argue that Rust might support tagged unions as language primitives, but that would be totally pointless as Result types are relevant for the interfaces and higher level abstraction they provide, not your personal opinion of how hard someone else had to work to implement them.

I've developed Result and Either types in a few languages, including C++, and the only hard thing about C++ is doing the usual homework to handle lvalur/revalue/revalue well.

Re:C++ by Example by ncmncm on Thursday September 22, 2022 @05:37PM (#32944945)
> it's just what it takes to do this in C++

False.

Re:C++ by Example by LegionMammal978 on Thursday September 22, 2022 @06:16PM (#32945334)
Do you have any examples of how std::optional could be implemented more simply?
Re:C++ by Example by ncmncm on Friday September 23, 2022 @12:27PM (#32954024)
The std::optional in MSVC was implemented in a language considerably behind current C++, for obvious reasons. The need to use template metaprogramming in implementations is much less, today.
Re:C++ by Example by LegionMammal978 on Friday September 23, 2022 @04:13PM (#32956509)
How so? Some of the "enable_if"s can probably be replaced with "requires" syntax, as well as the "conjunction_v"s and "disjunction_v"s, but the majority of the complexity seems to be in expressing the various requirements imposed by the Standard. Are there recently-added concepts (or other features) that would express them more naturally?
Re:C++ by Example by ncmncm on Thursday September 22, 2022 @12:51PM (#32941502)
The substantial performance overhead, in Rust, of code to handle those types is unavoidable, even where source-level inconvenience has been minimized.

Overhead is imposed all up and down the call chain, every time through. Seems pretty relevant to me.

Re:C++ by Example by mathstuf on Thursday September 22, 2022 @05:10PM (#32944678)
> So, in C++ you as library writer are empowered to make the use of your library correct by construction: what compiles is safe and correct

Empowered? Sure. But it seems no one likes using that power for long stretches of time. Rust gives the same power and it gets used far more usefully IME.

> Almost every C++ feature is designed to enable delivering more powerful libraries, and they compound.

Well, we can take `std::variant`, `std::optional`, and `std::expected` out of that pool because the committee hamstrung them from their better alternatives that already existed in Boost for silly, misguided reasons.

> Rust makes the compiler responsible for memory safety, but offers much less to make using your library pleasant and foolproof.

C++ libraries have, historically IME, been far more likely to ask you to juggle live grenades while dancing in a minefield than Rust libraries and APIs have.

Re:C++ by Example by alfiedotwtf on Thursday September 22, 2022 @10:56AM (#32939706)
Same here... I got through Stroustrup and thought I'm not smart enough to write this error free. Been happy with Rust ever since.
Re:C++ by Example by cyber_kinetist on Thursday September 22, 2022 @12:28PM (#32941211)
It’s all fun and games until you find the need to unsafe Rust, which opens up a bunch of eldritch monstrosities that are sometimes even harder to tame than C++.

The happiness people get from Rust was achieved by the incredibly hard work of library developers who had to deal with all sorts of complex semantics under the hood to make safe Rust safe. The knowledge gap between library user and library writer is even worse than C++, where most people do not feel comfortable enough to actually write low-level libraries (custom data structures, bindings from C, optimized routines) in Rust.

(At least PL people are inventing things like stacked borrows to make writing unsafe Rust easier… but it’s still not easy.)

Re:C++ by Example by unrealhoang on Thursday September 22, 2022 @02:47PM (#32943013)
on the other hand, that makes Rust's learning curve way way more gradual than C++. An intermediate programmer with 3 months of Rust experience can reliably and confidently cobble up the libraries together to contribute to the project. Whereas such programmer will be a heavy burden (for other seasoned devs to guide/review/feedback) in a C++ project.

Also, building low-level libraries that work correctly, efficiently, relatively-safely in C++ is NOT a simple feat, and requires years of experience (on API design). With unsafe Rust you can just fuzz/brute force out the unsoundness with the safe API.

Re:C++ by Example by spoiler on Thursday September 22, 2022 @06:23PM (#32945405)
> It’s all fun and games until you find the need to unsafe Rust, which opens up a bunch of eldritch monstrosities that are sometimes even harder to tame than C++

Lol what? Unsafe is literally the only "mode" in C++. I'm not trying to shill Rust, but this is not true, and I don't know where you've read that opinion. Unsafe Rust is just Rust with the ability to use "C++ style" pointers.

> The happiness people get from Rust was achieved by the incredibly hard work of library developers

I'll give you that writing Rust libraries is harder, but that's true for any language. Even C++. Do Rust developers go the extra mile to make libraries ergonomic and have nice APIs? Yes! But that's not really a "problem" with Rust, it's something Rust enables, and now the community expects. C++ libraries in my experience tend to be a very bare minimum, and to use some of them it requires hundreds of lines of set up code. In cases where Rust libs require that much set up code, the authors go the extra mile to create macros or additional succinct APIs. So, yeah, their job is harder because they are held to a higher standard than C++ libraries, if anything.

Also, most of the effort with authoring Rust libraries is writing documentation, which is practically a requirement, whereas with most C++ libs (even some sections of boost!) you practically weep tears of joy when you see five lines written above a one class in a sea of classes.

> who had to deal with all sorts of complex semantics under the hood to make safe Rust safe. The knowledge gap between library user and library writer is even worse than C++, where most people do not feel comfortable enough to actually write low-level libraries (custom data structures, bindings from C, optimized routines) in Rust.

Sorry to be so blunt and call you out, but this is just so devoid of any sensible thought.

Most people don't feel comfortable writing low level libraries. Period. Regardless of language. For every library author, there's dozens of not hundreds of non-libray developers. Hell, most developers don't even contribute anything to open source in general, but just consume it.

So pretending C++ is this magical fairytale land where everyone produces libraries with the flick of a wrist is just bullshit.

Re:C++ by Example by pjmlp on Friday September 23, 2022 @02:23AM (#32948681)
It is true, it certainly is.

Which is why, those of use that want some Rust like confort, when C++ is part of the diet, turn on bounds checking (#define _ITERATOR_DEBUG_LEVEL 1 on VC++), and make use of static analysis during the whole development (/analyze on VC++).

It is bullet proof? No, but it does help surving a couple of shots.

Re:C++ by Example by boppo1 on Thursday September 22, 2022 @04:42PM (#32944364)
Which Stoustrup, principles or the c++ language tome?
Re:C++ by Example by alfiedotwtf on Thursday September 22, 2022 @07:12PM (#32945849)
The C++ Language book. I enjoyed it up to the first half, but then was deer in headlights for the rest. Maybe it felt like all the rules were too big to fit in my head, but it personally felt like an overwhelming language.
Re:C++ by Example by a3w on Thursday September 22, 2022 @11:59AM (#32940801)
How do you fell about the pitfalls, like "if you inherit from a class, make sure the base destructor is virtual, or you just added a memory leak"

Some books on C++ teach you those, but I give up very early on learning languages with non-obvious expectations that offers few safeguards.

Re:C++ by Example by Chabsff on Thursday September 22, 2022 @12:04PM (#32940881)
That's not even particularly good advice, which just goes to show how subtle the pitfalls are. The rule really should be "If it is at all possible to delete instances from a pointer to the base class, then you need a virtual destructor". The overhead of adding a virtual destructor to a base class with no other virtual functions is far from negligible in many cases, so the distinction is meaningful (though modern guidance tends discourage non-polymorphic inheritance in the first place anyways).

The same thing goes for the good-old "Do not use raw pointers." The rule is actually: "Do not use raw pointers with implicit ownership semantics attached to them."

Re:C++ by Example by nyanpasu64 on Thursday September 22, 2022 @03:19PM (#32943437)
In retrospect I wish C++ used fat pointers rather than inheritance for virtual dispatch, like Rust but where interfaces/traits can have fields (Rust traits don't have fields and are less powerful than C++ base classes). This prevents accidentally overriding a base class method (eg. QWidget) by declaring a subclass method of the same name, eliminates the need to add a vtable pointer to object instances which you never cast to an interface pointer, and eliminates the need to juggle pointer offsets when performing multiple inheritance method calls, which can cause UB when performing C-style pointer casts and makes decompiling the code a nightmare (possibly fields in traits will add this requirement again, I'm not sure).
Re:C++ by Example by rramadass on Thursday September 22, 2022 @12:21PM (#32941112)
That is because C++ is not taught properly. It is not just a collection of syntactical features but a multi-paradigm language (i.e. supporting Procedural, Object-Oriented, Generic and Compile-time) where a feature is best suited to a particular paradigm and can also be used to express different concepts. Once you grasp this, things become quite clear and you understand how to design in C++.

To take your example; the same C++ "class" syntax can be used to express different concepts;

a) A user-defined value type eg. ComplexNumber. Therefore the dtor need not be virtual since the class is not designed for inheritance.

b) A pure interface used for "Interface Inheritance" i.e. all methods are "pure virtual". Therefore you need a pure virtual dtor. Java has the "Interface" keyword for this.

c) A class designed for a type hierarchy used for "Implementation Inheritance". Therefore you need a virtual dtor.

d) A class can also be used as a simple namespace eg. all static members; not designed for inheritance and thus no dtor needed.

Re:C++ by Example by bogomipz on Thursday September 22, 2022 @02:18PM (#32942655)
>"That is because C++ is not taught properly. It is not just a collection of syntactical features but a multi-paradigm language (i.e. supporting Procedural, Object-Oriented, Generic and Compile-time) where a feature is best suited to a particular paradigm and can also be used to express different concepts. Once you grasp this, things become quite clear and you understand how to design in C++."

Might you or someone else recommend a resource that does explain which features are suited for each the programming paradigms C++ support? Is there a modern resource that does teach it correctly like this? Knowing what features are relevant to your paradigm seems like a good way to approach learning C++.

Re:C++ by Example by rramadass on Saturday September 24, 2022 @07:42AM (#32961602)
C++ actually has two axes; 1) Paradigm axis (i.e. Procedural, Object-Oriented, Generic, Compile-time and Functional) and 2) Usage axis (i.e. Low-level bare-metal, Kernel, Library, Application). Every feature has an ideal application at the intersection of these two axes. Another way to look at it is how best to map concepts from the Problem-domain directly onto language features. Here techniques like Commonality/Variability analysis (bedrock of DDD, Patterns etc.) are used to express concepts using specific language features and then combine those into a coherent design.

Most of the above design ideas are found only in pre Modern C++ books. I don't know of any newer books which actually teach multi-paradigm design using Modern C++. So you will have to read the older books and then think about how you would map the same ideas into Modern C++. You might find the following useful;

Pre Modern C++:

1) Multi-Paradigm Design for C++ by James Coplien.

2) Scientific and Engineering C++: An Introduction With Advanced Techniques and Examples by John Barton & Lee Nackman.

3) Advanced C++ Programming Styles and Idioms by James Coplien.

4) Modern C++ Design: Generic Programming and Design Patterns Applied by Andrei Alexandrescu.

Modern C++:

1) Functional Programming in C++: How to improve your C++ programs using functional techniques by Ivan Cukic.

Re:C++ by Example by bogomipz on Saturday September 24, 2022 @10:36AM (#32962977)
Thank you for the wonderfully insightful and detailed response. This is really helpful. Cheers!
Re:C++ by Example by rramadass on Saturday September 24, 2022 @12:14PM (#32964035)
You are welcome.

For learning Modern C++, you might find these recommendations useful: https://news.ycombinator.com/item?id=32884432

Re:C++ by Example by kazinator on Thursday September 22, 2022 @01:51PM (#32942334)
Speaking of inheritance, how do you feel about this not requiring any diagnostics. It produces a weird result without containing any cast notation to subvert the type system.

  $ g++ -Wall -W -Wextra deriv.cc -o deriv
  $ ./deriv
  1.08654e-10

  $ cat deriv.cc
  #include <cstdio>

  struct Base {
  public:
    double y;
    Base() : y(1.0) {}
  };

  struct Derived : public Base  {
  public:
    int a, b;
    Derived() : a(0x3DDDDDDD), b(0x3DDDDDDD) {}
  };

  int main()  
  {
    Base *b = new Derived[5];
    b++;
    std::printf("%g\n", b->y);
  }
Re:C++ by Example by gpderetta on Friday September 23, 2022 @04:28AM (#32949342)
This is bad, but it is really no different than:

    int * b = new int;
    *++b;
Dereferencing past the end is always UB in C and C++ and it is hard to fix at the language level when using raw pointers.
Re:C++ by Example by jahnu on Thursday September 22, 2022 @02:16PM (#32942633)
For me this is the least of c++’s problems. Today I wouldn’t let that past a review as it should be using a std::array. If a c++ dev has a reason to drop down to this unsafe code they should know what the consequences are.
Re:C++ by Example by ncmncm on Thursday September 22, 2022 @01:04PM (#32941691)
Inheritance is a specialist technique, use of virtual members moreso. Most destructors in modern C++ are left to the compiler to generate.

It has been years since I last coded a virtual destructor.

Re:C++ by Example by tejohnso on Thursday September 22, 2022 @12:39PM (#32941352)
You'd want to read more than one book. And in my opinion you also need to digest the C++ Core guidelines and also use something like clang-tidy with high sensitivity, and when issues are flagged go dig into the details.

But then you realize it's just all too much, and you're looking for something less complex again.

I wonder how useful a C++ that I could understand in its entirety would be. But I don't understand english in its entirety either. I use what I know and get by just fine.

Re:C++ by Example by medo-bear on Thursday September 22, 2022 @01:29PM (#32942031)
> As my first language, I've yet to experience another language that genuinely lets me be as creative as C++

common lisp is cpp's way more talented brother that got addicted to lsd and became a hippy

Re:C++ by Example by mattlondon on Thursday September 22, 2022 @01:49PM (#32942304)
Try modern pure JavaScript. It's like floating through air. An absolute joy to code in.

Of course if you want to talk about performance and stuff then JavaScript is not comparable, but that is not the point

Re:C++ by Example by layer8 on Thursday September 22, 2022 @03:50PM (#32943793)
The lack of static typing will be a non-starter for many.
Re:C++ by Example by colejohnson66 on Thursday September 22, 2022 @11:19PM (#32947622)
TypeScript
Re:C++ by Example by intelVISA on Thursday September 22, 2022 @09:31PM (#32946932)
What eldritch horror am I going to unleash thanks to g++ today?

But I agree, C++ is the paintbrush of coding and I grow tired of my Js crayon prison.

Re:C++ by Example by kazinator on Thursday September 22, 2022 @01:55PM (#32942385)
There are hundreds of ways to do something, each one more importunely verbose and loaded with extraneous syntax than the next.
Re:C++ by Example by latenightcoding on Thursday September 22, 2022 @12:32PM (#32941264)
don't worry Perl will let you be 100 times more creative