11 ms·
C++ by Example
- agomez314 4y agothis page reminds me of https://learnxinyminutes.com/ https://learnxinyminutes.com/
- MatthiasPortzel 4y agoLearn X in Y minutes in my go-to when I’m writing code in a new language. Just the examples of syntax of a language are very useful and surprisingly hard to come by in formal documentation.
- scaredginger 4y agoHmm, not sure I'd trust this. I took a look at the shared_ptr page and didn't see it mention reference cycles or weak_ptr https://cppbyexample.com/what_is_shared_ptr.html https://cppbyexample.com/what_is_shared_ptr.html
- MauranKilom 4y agoThe site is very clearly not a complete guide, and has to leave out 90% of what a competent C++ programmer should know about any given topic (in order to remain accessible). I mean, the word "undefined" only appears in two of the examples. 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.
- scaredginger 4y agoYeah idk, I prefer when C++ teaching resources tell the reader where the bodies are buried. I couldn't give this to juniors and trust them not to leak memory 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
- planede 4y agoI have an other gripe with that page: > [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.
- deadbeeves 4y agoIt seems more robust to just make std::make_*() a friend function than to pepper the code with news.
- planede 4y agoI agree. If you can, just use the make_* functions. It also reduces needless repetition. For `make_*<Widget>(args...)` I need to write the type once, for `*_ptr<Widget>(new Widget)` I need to write the same type twice. Not counting cases for `Base/Derived`.
- MauranKilom 4y agoThat only works if `std::make_*` is actually where `new` is called. It could just as well be called deeper in some library implementation detail like `std::__gnu_cxx_v3::__construct_as(...)` (made up example), in which case you're SOL.
- MauranKilom 4y agoI like it. It uses uncomplicated language, doesn't try to frontload you with the complexity beneath, and shows clean and well-principled code (e.g. no `using namespace std;` - they say that all code snippets compile). 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.
- arberx 4y agoAs 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.
- Chabsff 4y agoAnd 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.
- synergy20 4y agoor 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.
- Chabsff 4y agoC++ 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++.
- arberx 4y agoThe "official" reference if anyone is interested: https://en.cppreference.com/w/ https://en.cppreference.com/w/
- planede 4y agoDefinitely the best C++ reference. It's not official in the sense that it is not the authoritative standard text itself, but it is very precise and complete.
- qsort 4y agoDefinitely THE website to bookmark if you're interested in C++ at all. 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.
- ncmncm 4y ago"Official", quote, alludes to very active curation by participants in the standardization process, with example code frequently updated to reflect changing best practice. 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.
- anta40 4y agoAnd for those who want offline copy: https://en.cppreference.com/w/Cppreference:Archives https://en.cppreference.com/w/Cppreference:Archives
- jdlyga 4y agoI always loved C++ as a language. Most of the use cases for it nowadays are when performance is key, and people use python for everything else. But I miss the structure that C++ provides without the heavy hand that Java and C# require. I definitely do not miss memory leaks and investigating core dumps though.
- ncmncm 4y agoGood news, with modern usage, memory leaks are a thing of the fast-receding past. Occasion to investigate core dumps is lately vanishingly rare. (I have spent strictly more time filing compiler bug reports, in recent years, than debugging memory usage violations.) 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.
- TillE 4y agoYeah I literally have not had a single memory leak since I started using unique_ptr and shared_ptr everywhere. I have had a couple resource leaks with C APIs, though even they could have been avoided with unique_ptr and a custom deleter.
- deleted 4y ago[deleted]
- photochemsyn 4y agoNice educational resource. Things like this help a lot relative to cppreference which often assumes the reader knows many things already. For example: https://cppbyexample.com/what_is_unique_ptr.html https://cppbyexample.com/what_is_unique_ptr.html https://en.cppreference.com/w/cpp/memory/unique_ptr 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.
- stall84 4y agothis is great
- DethNinja 4y agoSo far I’ve used six languages to build everything from web apps to desktop applications and C++ is still by far my favourite language. 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.
- pjmlp 4y agoThe problem is that many keep teaching C++ with code that a C compiler won't have any issues with. That is why Bjarne keeps doing those advocacy talks about best practices.
- ModernMech 4y agoThe real problem as I see it is that people think the path to safe C++ is to tell everyone "you're holding it wrong" (just use modern C++), when it fact being able to hold it wrong is regarded as a feature (C++ maintains backward compatibility) by the C++ community.
- pjmlp 4y agoBy C expats on C++ country.
- mk89 4y agoRelated to this, maybe: an issue I had was also the fact that online many of the help pages are really outdated. 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#r3-a-raw-pointer-a-t-is-non-owning https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines...
- deleted 4y ago[deleted]
- jjtheblunt 4y agoI must be a Scheme "snot", because the definition of "lambda" in C++ (and other languages) is not semantically what lambda in Scheme is. (There's a different definition of closure than in Scheme, with different implications as a result.)
- ncmncm 4y agoC++ lambda is particularly adapted to the needs of C++, and C++ programmers. It would be very surprising if it matched any Lisp's. Lisps differ from one another, too.
- threatripper 4y agoIn Firefox the code text is only readable in dark mode. In Light mode it's dark grey on black with a bright page around it.
- planede 4y agoThis looks like a nice start for a good guide. Some hierarchy for the examples would be nice, instead of an alphabetically sorted list. There are some minor inaccuracies here and there, but overall looks alright.
- ComplexSystems 4y agoI'm surprised this comments section isn't made up of people talking about how we should never use C++ again and only use Rust from now on.
- ncmncm 4y agoThat only happens in specially marked Rust-advocacy posts. 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.
- tialaramex 4y ago
- deleted 4y ago[deleted]
- pjmlp 4y agoWe should minimize the use of C and C++, and use safer languages instead, regardless of which. 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.
- hemloc_io 4y agoIs there something like this for Java? 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/ https://lib.rs/ but try doing "libs for java" and uh, it's not great.
- saghm 4y agoI think that probably has more to do with the fact that Rust libraries basically all come from the same place, since there's been centralized package management since the very early days. It's a lot harder to support something like that after the fact than designing for it in advance; new languages like Rust have an advantage in that regard.
- exisvr 4y agoCool site! I rarely use C++ now, but I still miss C++ from time to time!
- frozencell 4y agoThey should do: C++ by Problems.
- ur-whale 4y agoWhere's the template metaprogramming section? 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.
- jvanderbot 4y agoYeah, it's fairly basic, and most of this is in the usual c++ docs like cppreference.com But... Is template meta-programming a required feature of a C++ dev? double-bracket is ... an edge case of usual [] overloading, isn't it?
- ur-whale 4y agoThese are just examples to make a point. And: https://arne-mertz.de/2016/12/modern-c-features-attributes/ https://arne-mertz.de/2016/12/modern-c-features-attributes/
- stonemetal12 4y agoTemplates are a major feature of the language, leaving it out seems a little weird.
- d_tr 4y agoLooks like an ongoing work so more will probably be available in the future. I see an example for templates. Template metaprogramming is more advanced but would be nice to include.
- sva_ 4y agoThese? https://cppbyexample.com/templates.html https://cppbyexample.com/templates.html
- ur-whale 4y agoThat's just templates. I'm talking about stuff like this: https://en.wikipedia.org/wiki/Template_metaprogramming#Static_Table_Generation https://en.wikipedia.org/wiki/Template_metaprogramming#Stati...