28 ms·
Learn Modern C++
- throwuxiytayq 3y agoThe introductory tutorial comes with a GitHub repo. Chad move. Makes it easy to put on my e-reader. https://github.com/cpp-tutor/learnmoderncpp-tutorial https://github.com/cpp-tutor/learnmoderncpp-tutorial
- tcfhgj 3y agoWhen you are finished there, you can continue learning Modern C++ here: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
- jenadine 3y agoThe tutorial starts with cout << "Hello, World!" << '\n'; But the most "modern" way to write to the console is: std::println("Hello World!");
- nalgeon 3y agoMaybe one day someone will rate all "Modern C++" tutorials according to their level of modernity :)
- pokler 3y agoThis is from C++23, right? I wonder how available this is within compilers and how many shops plan on moving to this version of the standard and how long that will take. I imagine targeting C++17 or 20 for 'modern' would be practical enough considering thats what you are most likely to run into in a professional setting.
- steveklabnik 3y ago> This is from C++23, right? std::println is, yes. > I wonder how available this is within compilers https://en.cppreference.com/w/cpp/compiler_support https://en.cppreference.com/w/cpp/compiler_support says clang, gcc, and msvc all support it, though I don't know how recent those versions are off the top of my head. In my understanding, with this specific feature, if you want a polyfill for older compilers, or to use some more cutting-edge features that haven't been standardized yet, https://github.com/fmtlib/fmt https://github.com/fmtlib/fmt is available to you.
- wiseowise 3y ago> says clang, gcc, and msvc all support it, though I don't know how recent those versions are off the top of my head Where did you find it? Search by println yields no results.
- steveklabnik 3y agoFormatted output library <print>
- wiseowise 3y agoThanks!
- scatters 3y ago> I don't know how recent those versions are gcc 14 has not yet been released; going by past years, 14.1 should come out around the start of May (2024). clang 17 was released September (2023); note that you need to use libc++ (stlib=libc++), not libstdc++. VS 2022 17.7 has been out since August.
- gdiamos 3y agoWhen did that happen? I used to write a lot of C++, but it's been years since I've had to use it everyday.
- jenadine 3y agoThis year (C++23)
- pauljurczak 3y agoIt has not happened yet...
- tejohnso 3y agoI immediately thought your critique would be to use std::endl instead of '\n' I was reading a lot of c++ core guidelines and modern c++ blogs and books while writing a little game a couple of years ago and std::println was definitely not the common suggestion for modern c++. I see it's probably because it wasn't even available at the time. Now I feel like I'd have to review everything that I thought was modern two years ago to confirm that it is still the modern way.
- jb1991 3y agostd::endl is actually not advised most of the time. Using \n is the better alternative unless you need a buffer flush.
- dundarious 3y agoIf stdout is going to a terminal (i.e., it hasn't been redirected to a file), then the standard library will by default flush on every '\n' anyway. Similarly for C with fputs, etc. In C you control this with setvbuf, and of course, in C++ with iostreams it's a huge mess of rdbuf spaghetti and probably involving std::ios_base::sync_with_stdio as well.
- fooker 3y agoThis is wrong, stdout is not flushed by default on every newline. You can observe this by printing out tens of thousands of lines with vs without explicit flushing, there will be a big performance difference.
- dundarious 3y agoEdit: My C preference and iostream hatred is showing again, because I answered a question that was mostly about C++ iostreams with results based around C stdio (I think iostream is possibly the worst standard IO API in existence for a popular language, so when using C++, I recommend using something custom calling out to OS syscalls or C stdio). I could easily be wrong about C++ iostreams, so the most relevant half of my original post is highly suspect. I'll test it out later, but my C stdio answer is as-is below. I've tested that I'm correct on glibc, where the behavior is documented here: https://www.gnu.org/software/libc/manual/html_node/Buffering-Concepts.html https://www.gnu.org/software/libc/manual/html_node/Buffering... I can't remember using an alternative platform that behaves differently. A better test than the one you ran is to look at the resulting syscalls from a loop of `fputs("a line of output.\n", stdout);`, vs. `fputs("a bit of output. ", stdout);`. Buffering accumulates strings in memory before an eventual write syscall, so looking at syscalls is an easy way to see the difference: a write per-'\n' means line buffering. Compare the syscalls of both using strace. I did so, and when stdout is to the terminal, I see lots of calls to `write(1, "a line of output\n", 17)` compared to `write(1, "a bit of output. a bit of output"..., 1024)`. (To confirm, manually insert an `fflush(stdout);` in the "a bit of output. " version, and you'll see lots of `write(1, "a bit of output. ", 17)`) Then compare both when redirecting stdout to a file, and you'll see both cases make large write-s of 4KB. Only adding explicit fflush-es will make either version go back to small write-s of 17B. Compiled the trivial test programs with `cc -O2 ./main.c -o ./main`
- beached_whale 3y agoThat doesnt work on a majority of systems yet. Heck, gcc 14 gets it in the 14.1 release next year.
- pauljurczak 3y agoTrue. This is not a modern C++. It is a futuristic C++. Use {fmt} library in the meantime.
- beached_whale 3y agoI feel modern c++ is not so much mew features, save a few like move, but embracing guarantees with things like raii types.
- bdw5204 3y agoWhat is the rationale behind changing how print statements work in C++? Is there something broken about using cout or is this just another case of C++ adding extra ways to do the same thing for the sake of adding extra ways to do the same thing? The only significant difference I see is that std::println automatically includes the newline which may or may not be desired behavior.
- maccard 3y agoiostreams were a mistake, is the shortest way to sum it up.
- f1shy 3y agoAbsolutely! Glad to see it ending
- vitaut 3y agoDid you mean endling?
- pauljurczak 3y agoNo, he meant backslashend.
- pjmlp 3y agoNot for everyone, iostreams are great.
- steveklabnik 3y agoWhat's fun is, because everything is decided in papers, we can find out why! https://github.com/cplusplus/papers/issues/884 https://github.com/cplusplus/papers/issues/884 Accepted paper here: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p2093r14.html https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p20... > The proposed std::print function improves usability, avoids allocating a temporary std::string object and calling operator<< which performs formatted I/O on text that is already formatted. The number of function calls is reduced to one which, together with std::vformat-like type erasure, results in much smaller binary code (see § 13 Binary code). Additionally, > Another problem is formatting of Unicode text: > std::cout << "Привет, κόσμος!"; > If the source and execution encoding is UTF-8 this will produce the expected output on most GNU/Linux and macOS systems. Unfortunately on Windows it is almost guaranteed to produce mojibake despite the fact that the system is fully capable of printing Unicode
- einpoklum 3y agoThat's the modern-modern C++ :-) More seriously, though - the language is changing gradually: Features are introduced (and rarely, deprecated); and the missing bits of the standard library are added. C++11 was a _very_ significant change - but not to how you print output. C++20 and C++23 introduced `std::format` and `std::print`.
- angiosperm 3y agoC++20 is as big a change as C++11. It is almost as much more pleasant upgrading to C++20 as was upgrading to C++11. As more of the C++20 features get implemented in the compiler you use, the experience will continue to improve. Many people can already write "import <std>;" instead of many lines of "#include <...>".
- NekkoDroid 3y agoits `import std;`, without the angled brackets. Just make sure you are using the namespaced fixed integer types if you do :) else you still need `import std.compat` which is basically the c-headers
- tobinfricke 3y agoVery Pascal-esque
- moffkalast 3y agoGod forbid it actually figures out what the type is and prints it out properly like every other language in existence? If so I'm sold.
- bingo3131 3y agoYes. The main feature this is built upon is C++20's new string formatting features (very heavily inspired by the third party libfmt). C++23 just adds convinience functions to format and print at the same time. Type detection, formatting options, positional-arguments, custom formatters for custom types and probably more are all supported.
- UncleOxidant 3y agoThis comment right here is modern C++ in a nutshell. The most "modern" way will likely be different next year.
- angiosperm 3y agoBut either way is fine.
- fsloth 3y agoYou don’t need to keep up with the joneses to write C++. The whole point with the language is that it’s for millions of lines of code that exist for decades and you don’t update every line every time the standard is updated. Most existing code probably uses output streams with << operators, it’s good to know what that does.
- f1shy 3y agoI‘ve hated cout from day 0. happy to learn this. Thanks!
- inetknght 3y ago> But the most "modern" way to write to the console is: Indeed, as mentioned [0] at cppcon 2022 :) [0]: https://youtu.be/eD-ceG-oByA?list=PLHTh1InhhwT6c2JNtUiJkaH8YRqzhU7Ag&t=4980 https://youtu.be/eD-ceG-oByA?list=PLHTh1InhhwT6c2JNtUiJkaH8Y...
- 3836293648 3y agoSure, but that still doen't have compiler support in compilers people actually have
- pjmlp 3y agoNot for portable code, C++23 is still quite far from being widely available.
- deleted 3y ago[deleted]
- asicsp 3y agoSee also "Modern C++ Programming Course" https://github.com/federico-busato/Modern-CPP-Programming https://github.com/federico-busato/Modern-CPP-Programming
- jimbobthrowawy 3y agoIt'd be nice to have next/previous links somewhere on the page to navigate between the entries which are meant to be read in order.
- harporoeder 3y agoI feel that modern c++ is a game of how many times you can fit `const` in a single declaration. I usually have at least three for the simplest of functions.
- maccard 3y agoConst in C++ is probably one of the biggest frustrations I have with the language. It's an API promise, but suffers from all the downfalls of "what colour are your functions". Combine that with aliasing, const_cast, mutable, you're left with a pinky promise, with code duplication that I honestly wonder sometimes if we're better off without
- einpoklum 3y agoThen, in typical C++ form, I'll tell you that you are probably "doing it wrong". Just avoid const_cast and mutable in your application code altogether. Keep the const safety and the const will keep you safe :-) . Well, somewhat, granted. There is aliasing; and the fact that `restrict` is not formally part of the C++ is a pain point for sure. As for the code duplication, that's partially alleviated by a language feature introduced in C++23: deducing `this` https://youtu.be/eD-ceG-oByA?si=L5XIOpsQLYVT-laP&t=1045 https://youtu.be/eD-ceG-oByA?si=L5XIOpsQLYVT-laP&t=1045 and another part of it is addressed by adhering to the "rule of zero": https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-zero https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines...
- maccard 3y agoThe problem is that if I write struct Foo { int Bar(const Baz& b1, const Baz& b2) const; // ... }; The compiler can't reasonably do anything helpful with it _because_ of the above rules. Once you peek behind that curtain, it kind of crumbles. > As for the code duplication, that's partially alleviated by a language feature introduced in C++23: Agreed about deducing this, it's a bit awkward but solves a real pain point.
- 3y ago
- nox100 3y ago[flagged]
- a1o 3y agoMake unique was something that you could sort of do in c++11 (with tiny header) and officially added in c++14. All the other stuff you mentioned as far as I can tell is C++11 too, so it looks like you haven't used c++ for a long time.
- nox100 3y agoThat's not the point. The point is you shouldn't need that crap in the first place.
- binary132 3y agostd::forward<Self>(self) ok that's pretty goofy
- gpderetta 3y agoBecause a lot of things are not solved at the language level as the language is bloated enough as it is. Instead they are pushed into the library. Of course if the language was designed again from scratch it might settle on a different local optimum. From your example above, the only bit I really dislike is the handling of universal references (forward and &&), but that's the best that programmers better than me were able to retrofit onto the language, so eh.
- vitus 3y ago(Context: https://learnmoderncpp.com/2022/12/07/applications-of-c23s-deducing-this/ https://learnmoderncpp.com/2022/12/07/applications-of-c23s-d...) While the article describes why you'd want this abomination, honestly, I'd rather opt for the copy-pasted code T& at(size_t x, size_t y) { return data.at(y * X + x); } const T& at(size_t x, size_t y) const { return data.at(y * X + x); } as something that's actually human-legible while also providing const-correctness. If the implementation is actually complicated enough, then sure, use the const_cast variation, but hide it away in a .cc file. This feels like a contrived example to show off new language features. That said, I'd also rather use std::mdspan [0] if I had C++23 available, and not implement my own Matrix struct by hand. [0] https://en.cppreference.com/w/cpp/container/mdspan https://en.cppreference.com/w/cpp/container/mdspan
- kajaktum 3y agoC with classes is peak C for me. C++ is best when it is fixing C, not when it tries to be something else entirely.
- rlawson 3y ago100% agree!
- uecker 3y agoC is peak C for me. I think you can better modularize in C than in C++ because with APIs build around incomplete struct types the implementation stays in the C file and does not leak into the header as with classes.
- sevagh 3y agoThe last I checked in C++, you need to use the PIMPL (private implementation) idiom for that behavior: https://en.cppreference.com/w/cpp/language/pimpl https://en.cppreference.com/w/cpp/language/pimpl (not my favorite)
- uecker 3y agoThe C header interface is simple: struct foo; struct foo *foo_alloc(); void foo_do_something(struct foo *p, ...); This gives a simple to understand API with clearly defined boundary, has a stable ABI, preserves fast compilation times, avoids instruction bloat, etc. One could do this in C++ too, but what would be the point of using C++ then...
- angiosperm 3y agoYou can use incomplete struct types in C++ as easily as in C. If you are hiding implementation, the struct will likely have a single data member struct private_impl_type; std::unique_ptr<private_impl_type> impl; If you choose this, you trade off optimization opportunities. Your choice.
- senderista 3y agoFor me the only truly compelling C++ features are RAII and generics (not classes or virtual functions), and those are compelling enough for me to not consider C when I can choose C++. From what I can tell, the Rust designers seem to have felt the same way.
- vicss 3y ago[dead]
- binary132 3y agoRust posts on HN generate drama because of Rust People bickering with Anti-Rust People. C++ posts on HN generate drama because of C++ People bickering with C++ People.
- klipt 3y agoC++: Do I contradict myself? Very well then I contradict myself, (I am large, I contain multitudes.)
- binary132 3y agoA foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines.
- synergy20 3y agovery true, which is one reason why I keep using c++
- deleted 3y ago[deleted]
- Usingless 3y agowhat about https://www.cprogramming.com/ https://www.cprogramming.com/?
- angiosperm 3y agoGood if you like coding bugs.
- Usingless 3y agothen any books/resources u can recommend?
- angiosperm 3y agoTo write C is to code bugs. So, pick a different language.
- Usingless 3y agoquants use mainly or only c++
- angiosperm 3y agoRight. Use C++.
- 7thaccount 3y agoHonest question here. How hard and frustrating is it to keep up with all this junk? As someone familiar with nearly a dozen scripting languages, I keep trying for something low level like C++, but it seems like these languages are impenetrable at times. It's hard enough to learn the machine stuff and manual memory management, but having the syntax change more often than a toddler's favorite color just makes it all seem impossible.
- pompino 3y agoWhy do you feel the need to use every single feature? Are you constantly joining new projects that use vastly different features? Most programmers find a handful of features that gets the job done, and keep using them. Your knowledge from 10 years ago (C++11) is still valid and useful.
- 7thaccount 3y agoMy problem is more about how to get started and use certain scientific libraries. Maybe I just need to dive in. I keep getting detered though when I find out that simple things like iterating through a text file seem to take up so much code. Then I need a dictionary and somehow have to figure out how to get that. Not trying to whine. It's going to be a lot of work though lol.
- protomolecule 3y agoGPT-4 can be a good help here. It mostly gets simple things right.
- Buttons840 3y agoIn one of Bjarne Stroustrup's books he recommends focusing on software engineering rather than learning every language feature, or something to that effect. I think it's good advice. (And it's a good coping thought, but no less true.) An actual engineer or carpenter doesn't master every conceivable tool before beginning their work, they can't, there's too many. Say what you will about C++ programmers, but at least they are free from the burden of trying to use a perfect language and can focus on more important things.
- aragonite 3y agoAs someone who strongly regrets the fact that most programming languages arbitrarily restrict valid identifiers to Unicode "word characters" (ID_START and ID_CONTINUE), I was pleasantly surprised to discover the other day that, like Racket, Clojure, Julia and Swift, you can use emojis and pretty much any Unicode symbols in C++ identifiers!
- scatters 3y agoWe walked that back, sorry. http://eel.is/c++draft/diff.cpp20.lex#1 http://eel.is/c++draft/diff.cpp20.lex#1 Change: Previously valid identifiers containing characters not present in UAX #44 properties XID_Start or XID_Continue, or not in Normalization Form C, are now rejected. Rationale: Prevent confusing characters in identifiers. Requiring normalization of names ensures consistent linker behavior. Effect on original feature: Some identifiers are no longer well-formed.
- aragonite 3y agoArrg!! You can't rely on anyone these days. Oh well, at least these symbol-like characters which I've collected for use in Javascript (which has almost the same rules) should still work! ⴵ ⵛ ꘜ ⵣ ꕤ ꖜ ꘖ ꧮ ⴲ ꘖ Ⰴ Ⰺ
- secondary_op 3y ago[flagged]
- deleted 3y ago[deleted]
- csk111165 3y agoLooks clean! Just was wondering which framework/service do you use for hosting these md files? I am asking as I find myself motivated to host my own site like this consisting of mdfile.
- deleted 3y ago[deleted]
- w10-1 3y agoIt's extremely hard to write good tutorials. This one is very clear, but seems to have no time budget or reader model. I appreciate the clarity and the extensiveness, but it mainly makes me wish for something different. Today there are so many IDE's and online coding environments, godbolt, Swift playgrounds, golang interactive tutorials, etc. It would be lovely to see a C++ tutorial join that trend. I find the tutorial unsettling from the first words: `original, self-contained`. My first step in writing a tutorial would be to link the current state of the art, and the last would be a section pointing users to further resources, if my goal were not to trap readers but to help them. (Originality is a tall claim as the internet spawns LLMs.) Without any orientation to the landscape, the tutorial proceeds step-by-step with topologically-sorted vignettes that explain themselves verbosely. hello-world is prefixed by a long explanation why people start with hello-world, and following by 16 paragraphs of (to me) excruciating hand-holding and suggested experiments, without re-quoting the code. It's like pair-programming with someone who tells you what to type. The original K&R book was breathtakingly brief, mainly just showing you how to do things. Effective C++ neatly crystallized specific problems and solutions. Both benefited most by what they left out. Outside of an interactive tutorial for newbie's, what's needed for "modern" C++ is an origin story for each feature: what motivated it, how backwards-compatibility shaped it, what design decisions were made, how well it has been implemented and used -- ideally with bonus comparisons how Rust and Swift and Go managed the same issues. I think that would help people remember the complex issues and the syntax, and how to use it. To me most of the discussion from the C++ originators is more expository than explanatory: `for each opinion, explain in detail with cross-references to other opinions` - the political template. But readers only need to know the distinctions that make a difference in when and how they use a feature. Actual users are busy and paid only to get things done, not sling words. Users who value their time will pay for a good resource.
- deleted 3y ago[deleted]
- subharmonicon 3y agoI’ve been using C++ since the late 80’s and for the last 15+ years it’s been reluctant and only due to the projects I’ve worked on and the people I’ve worked with. I’d love to be in a position to work on a new project using Rust or Haskell instead.
- csk111165 3y agoI guess, we already have *www.learncpp.com* which includes most of the topics mentioned in moderncpp.com
- mebassett 3y agowhy would someone learn c++ in 2024, assuming one is not about to work on legacy projects? I'm about to start a quixotic new personal project and was considering using (read: learning) c++ for it, but it feels like rust is getting all the new attention. (and I'm already spoiled by haskell and racket.)
- angiosperm 3y agoYou learn a new language to write programs in that language. Few want to pay you to code in Haskell, Rust, or Racket. It will be that way for a long, long time. In 2030 your list will be different, but people will still pay to have C++ code written. Your personal project might then turn out to be in what is considered a legacy language, as Ruby is now. But C++ will continue modernizing, and getting more pleasant to code in.
- oconnor663 3y agoThere are big parts of the industry where Rust still doesn't have much penetration, even for new projects. Games is a big example. Highly regulated, safety-critical code is another. I think Rust will eventually get there, but it'll be a while before it's a "boring" choice for these things.
- fooker 3y agoBecause interesting stuff is written in C and C++, far more than any other language in existence right now. Compilers, games, all of the backends of the current LLM revolution, control systems for interesting hardware. You would sabotage yourself if you choose not to learn how to use a possibly suboptimal tool that is an industry standard.
- fulafel 3y agoThe state of programming languages on GPUs.
- conradfr 3y agoI have not done a "desktop" program in 25+ years and never using C++ (or C), since then I'm mostly a web developer (PHP, Elixir, JS, Kotlin etc). I'm currently doing a C++ audio plugin with the Juce framework. This website has been a good resource, alongside https://www.learncpp.com https://www.learncpp.com But I was actually close to give up before using those two things: - https://github.com/nlohmann/json https://github.com/nlohmann/json : my plugin use a json api backend and the Juce json implementation is atrocious (apparently because of being born with a previous C++ version), but this library is GREAT. - ChatGPT 4. I'm not sure I would have "succeeded" without it, at least not in a reasonable time frame. ChatGPT 3.5 is slow and does not give good results for my use case but 4 is impressive. And I use in a very dumb way, just posing question in the web UI. I probably could have it directly in MSVC? Also I must say, for all its flaws, I have a renewed appreciation for doing UI on the web ;)
- AtlasBarfed 3y agoSoooo.. front and center of c++ ... Are string literals only 8 bit chars aka no real Unicode? The description danced around it so much it sounds like obfuscation
- hgs3 3y agoBoth C [1] and C++ [2] have string literal syntax for UTF-8, 16, and 32 strings. [1] https://en.cppreference.com/w/c/language/string_literal https://en.cppreference.com/w/c/language/string_literal [2] https://en.cppreference.com/w/cpp/language/string_literal https://en.cppreference.com/w/cpp/language/string_literal
- jocoda 3y agoLooking for resources on C++ for MacOS (GUI). Anyone?