243 points · by synergy20 · 4y ago · 119 comments
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.
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.
in modern c++, also teach RAII and unique_ptr, combined they can eliminate so many memory safety problems.
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++.
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.
Perl? Can even write poetry in it. https://docstore.mik.ua/orelly/perl/prog3/ch27_02.htm
[0] https://twitter.com/timur_audio/status/1004017362381795329
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.
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.
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.
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.)
Some books on C++ teach you those, but I give up very early on learning languages with non-obvious expectations that offers few safeguards.
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."
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.
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++.
$ 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);
} 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.It has been years since I last coded a virtual destructor.
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.
common lisp is cpp's way more talented brother that got addicted to lsd and became a hippy
Of course if you want to talk about performance and stuff then JavaScript is not comparable, but that is not the point
But I agree, C++ is the paintbrush of coding and I grow tired of my Js crayon prison.
And I say this as someone who gets a kick out of template metaprogramming.
Yes, you will commit atrocities if you try to learn C++ from just this resource. It is very much a nice facade around the bottomless pit that is C++. But in terms of getting someone started on their first small C++ projects, this is extremely to-the-point, and infinitely better than requiring people to dig through "how do I read a file" StackOverflow answers or needlessly elaborate articles that show terrible code "for the sake of exposition".
It might go against the intent of the site, but some kind of notice like "C++ is big and has many sharp edges, so you should eventually look to curate your understanding beyond this site" would round it out.
Recognized best practice changes with both experience and with newly implemented language features. New features are proposed, and some standardized, specifically because they enable better ways of coding. So, best practice may change markedly with each new Standard.
Generally, the newest way to do something is usually best, for exactly that reason. (A common misconception has one sticking with older language features for better code. The reductio ad absurdum of this would prefer the C subset.) This does not oblige you to use every feature in every program; e.g., std::shared_ptr has sharply limited value. And, the absolutely newest features may not be very portable yet.
Sometimes more field experience with a feature and its interaction with others leads to changes to best practice. This should be expected particularly in use of concepts and asynchronous facilities.
As an example of change, the present universal preference for "std::" vs "using" took a long time to gel because writers (of articles, slides, textbooks) begrudged the extra space it took on their page.
Examples found on cppreference may usually be relied upon to produce sound results and to steer well clear of both risky usage and bad performance.
Notice that due to SEO fuckery, your first search result might be cplusplus.com, which is not the same and not as good. cppreference.com is where it's at.
It is sad that it is still haunted by prejudice due to pre-C++11 era but modern C++ is easy to learn and use, and I recommend every programmer should give it a try.
That is why Bjarne keeps doing those advocacy talks about best practices.
I can't forget an old accepted "much voted" answer I saw on stackoverflow which claimed that raw pointers should be owning resources, because that's how the language always did.
I think the answer was dated like 2008 or so, can't find the reference anymore. That's when I started to pay a lot more attention to the published date whenever I search for help and I stumble upon a very old article. If only we could get rid of old resources written before maybe 2018-2019 and only select those that are still "modern", that'd be already a great step forward.
Luckily we have this now [0].
They should invest more in tools like the GSL extension at least as a clang warning which really helps, and things like that. That's how I believe Java was also able to modernize. You can write pretty crappy Java too, but tools like findBugs or checkstyle do help, so why not!
[0]: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines...
https://learn.microsoft.com/en-us/events/pure-virtual-cpp-20...
https://cppbyexample.com/what_is_unique_ptr.html
https://en.cppreference.com/w/cpp/memory/unique_ptr
The former spells out the rationale for the design - such as why you might need get or why make_unique is better than new, and why copies are forbidden but moves are allowed - that the official reference sort of assumes the reader already understands.
Today, it is fun to code in C++. Restricting it to performance-critical uses would be a bad mistake. Displacing C with simpler, more reliable, often faster C++ is an easy choice, but reaching for C++ in place of Python is also often a great idea.
I have had a couple resource leaks with C APIs, though even they could have been avoided with unique_ptr and a custom deleter.
> [about std::make_shared] This function is useful because objects might throw exceptions during construction and if they do we still need to call delete on the pointer we received from new otherwise we will leak the pointer.
This is oversimplified and just plain incorrect. There was never a possibility that a statement like `auto sh_ptr = shared_ptr<Widget>(new Widget);` could leak.
However possibility for leak existed for calls like `foo(shared_ptr<Widget>(new Widget), shared_ptr<Widget>(new Widget))`, because evaluation of function arguments were unsequenced. This hole was fixed in the language in C++17, where function arguments became indeterminately sequenced.
And possible advantage for `make_shared` is the shared allocation for the control block and the object. It is not a clear advantage, as remaining `weak_ptr`s keep the whole allocation alive, even after the object itself is destroyed. But I wouldn't include this to a tutorial.
One annoying place where you can't use `make_shared` and `make_unique` is for invoking private constructors, even in a context where you could use the private constructor directly (like a static factory function within the same class). Since `make_shared` and `make_unique` are typically not friends of your class, they can't call the constructor indirectly. There are some workarounds for this, but the easiest way is just to use `new` here, it's fine.
But I'd say it doesn't teach any bad (or outdated) habits, which is a big step up from most tutorials/articles/SO answers.
Agree balancing accessibility and comprehensiveness is difficult though. I could see an argument for leaving shared ptr out of this guide if they think cyclic referencing is too advanced, and I can also see the argument that without knowing shared ptr exists, the user may write hacks much worse to get around the problem
More people pick up C++ to use professionally in any given week than the total population of working Rust coders. Rust is practically invisible outside hipster media.
However in many domains the only mature options are C and C++, in which case my option will always be C++.
There are lots of areas where Rust is still quite behind managed languages and C++, in IDE tooling, libraries, infrastructure.
(There's a different definition of closure than in Scheme, with different implications as a result.)
I feel like the more popular languages get the more people write blogspam that gets in the way.
E.g. If you search "libs for rust" you get https://lib.rs/ but try doing "libs for java" and uh, it's not great.
What about the double bracket operator?
etc...
Or, to put it another way: very nice website for basic exposure but mostly demonstrates very basic stuff.
But... Is template meta-programming a required feature of a C++ dev?
double-bracket is ... an edge case of usual [] overloading, isn't it?
And: https://arne-mertz.de/2016/12/modern-c-features-attributes/