Modern C++: Unique Ptrs and Vectors

Sdílet
Vložit
  • čas přidán 3. 06. 2024
  • Dave takes you on a tour of the modern C++ features you need to know in order to avoid memory leaks, corruption, and other common pitfalls of using C++.
    Code: github.com/davepl/blackjack
  • Věda a technologie

Komentáře • 973

  • @CristiNeagu
    @CristiNeagu Před rokem +313

    More videos like this, please. I'd like to learn C++ but all these libraries and concepts required to understand how to use it properly are doing my head in. This video really helps clear things up.

    • @danman32
      @danman32 Před rokem +3

      Yep, me too

    • @CristiNeagu
      @CristiNeagu Před rokem +11

      @@J.D-g8.1 The problem with that is, like Dave said, that you're not working in C++, but rather in C with OOP. Going by what I saw in this video, learning manual memory management while learning C++ is completely the wrong thing to do. While that is a fundamental skill in C, in C++ it's a special case for advanced users, not one for beginners.

    • @samueltulach
      @samueltulach Před rokem +7

      @@CristiNeagu If you are using C or C++ you have a reason for it. Most likely this reason is that you need this direct memory management. For example I work primarily with Windows kernelmode drivers and guess what? std libraries do not exist there, but you can still use C++ to “make the code cleaner” with namespaces, classes (although you really don’t want to allocate classes on the go in kernel, so mostly static or some weird usecases) and templates. Sometimes I also write assembly code that’s just how it is. To be fair, there is also no libc for the most part so no malloc etc. but you get the point: if you are learning C++ it’s because you want to have maximum control.
      If you are doing literally anything else that does not require you to have this sort of control, then just use different language. Speed is not the top argument anymore these days since most crap gets AOT compiled anyway…

    • @jacobesplin20
      @jacobesplin20 Před rokem +1

      I am also interested in more videos like this. It would be really cool to know how these methods change performance?

    • @forbiddenera
      @forbiddenera Před rokem

      Agree! My cpp is weak these days

  • @bdp-racing
    @bdp-racing Před rokem +172

    I learned more in this 16 minute and 24 second video than I did in an entire month of drag and drop “programming” that they tried to teach in school. Thanks for making these videos and explaining everything in a way that’s easy to understand.

    • @JohnnieWalkerGreen
      @JohnnieWalkerGreen Před rokem +2

      Hear hear...

    • @sorbpen
      @sorbpen Před rokem +4

      @@JohnnieWalkerGreen Dave is such an awesome human.
      He not only built some of the systems that the world relies to, he keeps spreading the knowledge to the future generations.
      I don't know how much you have had experience with or practiced making presentations like this before you started youtube.
      But I can see that you have mastered the art of what information to leave in and what to present in such a wide topic as modern C++.
      This is granted with my basic understanding of the language, but I know wisdom when I hear it.

    • @NoNameAtAll2
      @NoNameAtAll2 Před rokem +8

      school level teaches what algorithm is, not how to program with memory control...

    • @TheInevitableHulk
      @TheInevitableHulk Před rokem +7

      Well clearly. Drag and drop is to ease complete beginners into the concept of programming. This video is about the nuances of memory management in c++.

    • @bakedbeings
      @bakedbeings Před 10 měsíci +4

      You can thank your school teacher for your ability yo understand this more advanced lesson.

  • @nicholasdark1270
    @nicholasdark1270 Před rokem +73

    Hi Dave, as someone with far too many years of embedded C experience, but only a couple of years of self taught C++ I'm still sort of in the wrapped C category. Though I do like and use Vectors wherever possible.
    If you are ever stuck for video ideas, then a C to modern C++ conversion course would be fantastic.
    Thank you for the constant stream of interesting and high quality videos.

    • @AspartameBoy
      @AspartameBoy Před rokem +3

      I learned C++ when it first came out of the closet. Back then the C++ compiler generated C code. At some point that feature was lost; we ended up with the whip cream coated hotdog in play today. Just don’t try to use every feature🤣

    • @uploadJ
      @uploadJ Před rokem +2

      Imagine how I, a VB6 programmer, feels ...

    • @ForaPhil
      @ForaPhil Před rokem +1

      I’m a C with classes guy and proud of it. C++ is just too bloated imho. Besides if you need babysitting when writing code maybe you should use a higher level language like Java or C# in the first place.

    • @Shabbymannen
      @Shabbymannen Před rokem +2

      @@ForaPhil Right on. C++ started out as "C with classes", I think it was originally actually named that, and it was a great idea. Didn't catch on, and the solution was "add more features", and the result is the bloat we grew up with and learned to hate. Now, I haven't really looked at the language in 20 years, I'm strictly a C guy. I understand it has improved, BUT. There is something to actually being able to write solid code in C, not leaking memory, not doing off-by-ones etc. Being a good programmer. They should teach that to people. I agree there is no way using any set of library features is going to save anyone from sucking at coding. Classes is not the problem with C++, it's its redeeming feature.
      There is an old saying... "C is to C++ as lung is to lung cancer."

    • @arthurmoore9488
      @arthurmoore9488 Před rokem +3

      Embedded is rough, since you sometimes don't get the standard library. If you want to convert C to C++, my first suggestion would actually be to always compile using a C++ compiler on C++ version 20, or at least C++ 17.
      From there, take a look at "clang-tidy" and the "C++ Core Guidelines". That gives you plenty of things you can do to slowly convert your code. Like using `std::array` instead of C Style arrays.
      PS: `std::array` is for fixed size arrays, `std::vector` is for dynamic arrays.

  • @snobaste
    @snobaste Před 8 měsíci +5

    As someone who had modern C++ drilled into him by a person many years his junior, I appreciate this series for giving me the mirror opposite experience 😆 One very small nitpick, though: if you look at vector's implementation of push_back with an r-value reference, it actually just calls emplace_back using move semantics. I've found it a good habit to explicitly call emplace_back when your intention is to move an r-value reference into a vector!

  • @zactron1997
    @zactron1997 Před rokem +41

    I'd really like to see a follow-up to this that would show how a "C with Classes" style would write thw same program. I'm guessing it would simply replace the vector with an array, and the unique pointers with regular pointers, but it would be nice to go over exactly where the memory and aafety issues can arise.
    Also, I really hope you do a Rust video. The safety and performance of Rust is amazing, but it's actually the developer ergonomics and the ease in importing and project orchestration that makes me dread touching the C++ project I have to maintain.

    • @milk-it
      @milk-it Před rokem +2

      I'd love to see a video on how Dave would write this in C, too. I'm new to coding, but I was thinking along similar lines to you. A demonstration in C would show good memory management when driving in manual.

    • @toby9999
      @toby9999 Před rokem +4

      I spend a lot of time maintaining legacy C code that was "ported" to C++ but inherited all of the old C stuff. So it really did become C with classes.... and I not unsurprisingly spend a lot of time debugging heap corruption and other various memory management issues. It's a nightmare at times.

    • @arthurmoore9488
      @arthurmoore9488 Před rokem

      @@toby9999 Been there. It's especially fun when the original coders **assumed** that uninitialized variables are really zero initialized by the constructor! Amazingly doing web work in C# pays way better.
      Rant: I do miss being able to set "const" variables at runtime. C#'s "const" is like a more strict "constinit". While it does have "readonly", there's no function level equivalent. This code is impossible in C#: `const bool isOk = f()`. This is also impossible: `const string HELLO = "Hello World"`.

  • @scienceandmathHandle
    @scienceandmathHandle Před rokem +77

    std::vector.shrink_to_fit() is also one of the most underrated functions that exists if you know you are not going to expand it at once, or for not a long time.

    • @Grafiksocke
      @Grafiksocke Před rokem +6

      I am working on a performance and memory sensitive application and I will try this to see if it saves me some ram, thanks 🙏

    • @julienmarcuse9023
      @julienmarcuse9023 Před rokem +2

      wouldn't this need to reallocate? or does it just trim?

    • @JATmatic
      @JATmatic Před rokem +7

      @@julienmarcuse9023 It might do reallocation, it is implementation defined. Depends likely how much excess capacity the vector has.

    • @denkalenichenko4124
      @denkalenichenko4124 Před rokem +3

      ​@@JATmaticIm not sure, but C++ doesn't have own reallocate. Only C realloc

    • @zeez7777
      @zeez7777 Před rokem +4

      @@denkalenichenko4124 Yes so that is still c++, its a superset of C

  • @poushankumarbiswas8693
    @poushankumarbiswas8693 Před 10 měsíci +7

    Sir, you should now really start considering teaching here on CZcams. The explanations are one of the best ones we can get out there and especially when it comes from someone who has decades of experience in it. Full scale courses coming from you would definitely help us learn in the best way possible and will also make people fall in love with programming.

  • @systemloc
    @systemloc Před rokem +26

    That is such a great and straightforward example of the use for unique_ptr. Your epic mastery and years of experience shine through in how clean and clear everything is.

  • @rickpoeling6831
    @rickpoeling6831 Před rokem +12

    Excellent working example. Your coding style is extremely efficient and easily understood.

  • @delsorou8279
    @delsorou8279 Před rokem +20

    You can also put "using" at the top of any scope, for instance a single function in which you expect to type std:: a lot. Sort of a compromise between convenience and risk reduction.

  • @KeithCooper-Albuquerque
    @KeithCooper-Albuquerque Před rokem +4

    Excellent video, Dave! I'm retired now, but I had been programming in C++ since 1991. The STL is a wonderful thing indeed! Thanks for your channel!

  • @HyperFirezAlt
    @HyperFirezAlt Před rokem +9

    Amazing video. At my university, so far we've been basically taught "C with Classes" as you mentioned in the video. I have had some assignments involving Vectors but as I've already used ArrayLists in Java so it's nothing new to me. I have came across the new pointer types in modern C++ and read a bit on them, but this video made them very easy to understand and I really appreciate it!

  • @kebien6020
    @kebien6020 Před rokem +4

    I think this video has very good intentions, but it has some issues that I would like to point out:
    7:45 Avoid using plain enums in new code. Prefer enum class which declare separate types instead of declaring the equivalent of global variables of type int. With regular enums ACE == DIAMONDS produces true whereas with enum class Rank::ACE == Suit::DIAMONDS is a compiler error. (see C++ Core Guideline - Enum.3 Prefer class enums over “plain” enums)
    9:01 Although this example tries to illustrate the use of unique_ptr, this is a perfect example of when not to use it. Remember, a vector already puts it's storage in the heap, and already manages it's memory allocations and deallocations automatically.
    Aditionally, Card objects in this example are really small, so you really are better off passing them by value than by pointer anyway (easier to code, and better performance). But that misses the point of the example. I'm guessing that the idea is to imagine that Card objects are expensive to copy around. I just wanted to mention this, for anyone interested in applying this in real-world programs.
    9:18 This is right, but the vector will call the destructor of the elements in a loop. For unique_ptrs this is really slow because you're deallocating a bunch of objects one by one. For Card objects the destructor actually does nothing and the compiler optimizes this loop away. Then the whole memory of the underlying array is deallocated in one go (in both cases).
    9:44 There is no need to specify upfront the size, but in most cases you either know the size, or a decent estimate, which is good enough (in this case we know the exact size: 13*4). This is good to avoid "distributed fat". You can get a better explanation in this talk that you can find here in CZcams: `CppCon 2014: Chandler Carruth "Efficiency with Algorithms, Performance with Data Structures"` around 21:28
    10:53 You actually CAN have multiple pointer references to whatever a unique_ptr points to. They are just non-owning references. You do this by getting a raw pointer from the unique_ptr using the get() method.
    Contray to popular belief, raw pointers are actually fine in modern C++, you just have to avoid using them for memory management. You accomplish this by never calling new and delete manually. Other than that, raw pointers are just fine. (see C++ Core Guideline - R.3: A raw pointer (a T*) is non-owning).
    11:43 You might want to make the random device and the random engine objects static. Just to avoid constructing them every time that you call shuffledeck. Construction of these objects is fairly expensive, and just adding static does the trick for simple cases. For a thorough explanation, see the talk `CppCon 2016: Walter E. Brown “What C++ Programmers Need to Know about Header <random>"`
    12:55 std::move is pretty counter-intuitive and actually just does a type-cast. It might or might not trigger a move by changing the type, depending on the context where you call it. I think in this case we're not changing the type at all (the call to std::move does nothing, and can be removed), but the move still happens. Additionally, since the move happens, the unique_ptr in the vector is left in a moved-from state. But it is fine in the end though, because he does the pop_back right away, removing the moved-from object.
    The explanation saying that it would be fine even if left in the vector is wrong. It is undefined behavior (UB) to do anything other than detroying an object in a moved-from state. So if it was left in the vector, a sub-sequent drawCard() could draw that same card and then any operation on that drawn card would be UB (including the possibility of corrupting memory, though most likely you'll just segfault).
    More explanation in the C++ Core Guideline - ES.56: Write std::move() only when you need to explicitly move an object to another scope. For a thorough explanation, this is the talk: `Back to Basics: Move Semantics - David Olsen - CppCon 2020`.
    14:01 You're indeed never duplicating cards. But even if you use value semantics (aka. a vector instead of a vector ), which would involve copying card objects, you are still avoiding all of the pitfalls of manual memory management.

    • @Rexhunterj
      @Rexhunterj Před měsícem

      Thanks, there were some of these points I was thinking myself and you added some with references as to why that I hadn't known.

  • @TractorWrangler01
    @TractorWrangler01 Před rokem +23

    You are an excellent teacher Dave.

  • @brycesharp1796
    @brycesharp1796 Před rokem

    I always listen to your presentations, even if I dont have a specific need for the tech you are talking about, and I have never felt a minute was wasted. Thanks for sharing
    Dave.

  • @mogenshansen7210
    @mogenshansen7210 Před rokem +2

    Having followed your channel for some time and enjoyed it, I am so happy to see this kind of information presented in a simple, understandable and usefull way.
    The information you are giving, may very well be under utilized.
    Thank you so much
    Regarding the "modern" part, a fun fact is that I have been using vector (from the original STL) since 1994 (almost 30 years ago) and std::vector since C++98, smart pointers (std::auto_ptr and Boost smart pointer) since late 1990's. Move semantics and std::unique_ptr (from C++11 - 12 years ago) was a huge improvement.
    I am so impressed that Bjarne Stroustrup's RAII from the very early days of "C with classes" brilliantly holds up so well 40 years later.
    For almost 25 years I have promoting that "writing new/delete in C++ application code is almost always suboptimal and error prone".

  • @SassyToll
    @SassyToll Před rokem +5

    More videos like this please Dave, you are a great teacher and I always learn something from you. Thank you for all your hard work. John, Ireland 🇮🇪

  • @TheBowlingPotato
    @TheBowlingPotato Před rokem +5

    This is why I loved the programming competitions in school. You get no packages, you get no web pages to look up, you must know the language and what it offers, like std. Always loved watching the java guys tell me c++ is bad for string processing problems while mine worked and they never even reached submitting an answer. If you use your tool better, you'll still get better results, regardless of tool.

    • @maleldil1
      @maleldil1 Před rokem

      > you get no web pages to look up
      Maybe you're talking about different things, but ICPC contests allow you to bring reference material, and they usually have basic documentation stored in the computer too.
      > watching the java guys tell me c++ is bad for string processing problems
      Regardless of your other factors, this is still true. Java's String class is more capable and easier to use than C++'s. It doesn't mean you can't write your own functions, and I'm sure they work well, but the experience out of the box for Java is indeed better.

    • @mithrandirthegrey7644
      @mithrandirthegrey7644 Před rokem

      That sounds perfectly useless. Why handicap yourself like that?

  • @DogeOfWar
    @DogeOfWar Před rokem +1

    Thanks for the vid Dave, I just came across your channel and I notice this sort of stuff is a relatively new type of content for you, and I subbed and look forward to seeing more modern C++ features demonstrated!

  • @Christian-op1ss
    @Christian-op1ss Před rokem

    Hi Dave, as you asked to write a comment for a suggestion, my biggest issue in using C++ is that there are many many ways of doing things, and it is not very clear, even when looking for it, which options are obsolete or anti patterns, and which are good. This video goes a long way of addressing this issue for memory management, although there are of course parts missing to keep it from getting too long. But more videos such as this which tell us, topic by topic, how to do it in modern C++ and what to avoid would be fantastic!

  • @midge9740
    @midge9740 Před rokem +3

    Seriously thanks for this video. As a novice c++ dev with about 6 months worth of experience, its great to have my eyes opened to what a very experience dev has to say. I'd love to see more videos like this. Thanks :)

    • @jboss1073
      @jboss1073 Před rokem

      6 months is more than enough to master most programming languages, and you're still a beginner in C++ after 6 months, this shows that C++ is trash.

    • @midge9740
      @midge9740 Před rokem

      @@jboss1073 lol. I didn’t say beginner. And I haven’t had much motivation, so I haven’t actually put in all that much work. Idk what u would considering mastering a language, but I don’t think I should be there yet. What I meant by novice is that I don’t know the best practices of the language and all the newer features. Such as smart pointers. I know they exist but I’m not very good and knowing when to use them. C++ in my opinion is a very good language, and I’m not sure where you coming from calling it trash. Do you have any specific reasons? And what languages do you prefer?

    • @jboss1073
      @jboss1073 Před rokem

      @@midge9740 Not even programmers who have been doing C++ for 20 years are "there yet". Don't worry.
      If you want specific reasons for C++ being trash, please read the authoritative work of Ian Joyner. He not only has an entire book on specifically all the reasons C++ sucks (Objects Unencapsulated: Java, Eiffel, and C++), comparing it to a better OOP programming language, but I believe he also has a paper or some other summary that you can find online if you look for it. Sorry I can't remember where the summary is. C++ is not a good language by Computer Science standards. Racket is, by those standards. They're worlds apart. There is an objective way to judge how good languages are and C++ is not good.

  • @johnmckown1267
    @johnmckown1267 Před rokem +20

    Very interesting. I am a very old programmer. But not on UNIX or Windows, but "legacy" IBM z series hardware, back to S/370 days. I was introduced to C/C++ back in K&R times, on Windows 95. Nice to see the C/C++ language continuing to advance.

    • @Bilzie-rs6qt
      @Bilzie-rs6qt Před rokem +4

      I'm 23 and working on the new z16 mainframes. We haven't moved from HLASM and COBOL (to my chagrin, COBOL is terrible with the power of hindsight) and it's such a unique programming field now, I love it.

    • @lwilton
      @lwilton Před rokem +2

      @@Bilzie-rs6qt Out of curiosity, why do you consider Cobol terrible? There are a lot of things that it isn't good for or maybe worse than useless, but, in my experience, if you stick to things that are business problems (or even compilers) it is a bunch simpler and easier than a lot of algorithmic languages. (Personally, I award 'terrible' to Fortran.)
      I spent quite a bit of time writing programs in various assemblers, C, C++, Algol, various Algol-like languages, Cobol, Fortran, and a few other dinosaur languages. I'd generally try to pick the language based on the problem set, and I found Cobol to be the language of choice for quite a few problems.

    • @lucidmoses
      @lucidmoses Před rokem

      Are you sure? K&R died a very quick death with the introduction of ANSI C in 1989. Compiler manufacturers were tripling over each other bringing out ANSI C version before the standard was even officially released. Who build a K&R compiler for Win95? It does sound like something IBM would do. They were still supporting punch cards till 2012 (albeit mostly for voting machines).

    • @Bilzie-rs6qt
      @Bilzie-rs6qt Před rokem +3

      @@lwilton sure I can give you a quick overview:
      1. Variables are global scope. You can have hundreds of fields defined and use them anywhere in the program, which is complete clutter. It introduces the need to prefix your fields with x69420-my-cool-field to prevent shadowing, and if you need your cool field to store a temporary value for one procedure it is able to be read or written to from anywhere else too. Why should a temporary value have global scope?
      Typing on the phone is annoying so I'll just list out some more annoyances
      2. Paragraphs are worse than functions. The input and output is not clear and it just frustrates me.
      3. Syntax is overly verbose.
      4. Copybook are a clean but deadly tool. It can clean up your code but can silently introduce name collision and pasting paragraphs through copybooks is a sin.
      5. Naming conflicts. Say I have 2 structs.
      Vec2 { x: f32, y: f32} and Vec3 {x: f32, y: f32, z: f32}. In most languages you can have both these definitions and use them no problem as members. But COBOL has trouble with this because you normally referece the member directly (global scope), so you have to reference it has X of Vec2 etc.
      6. COLUMNS/AREAS SUCK
      I think that will do for now

    • @johnmckown1267
      @johnmckown1267 Před rokem

      @@Bilzie-rs6qt Being verbose was a design decision. COBOL was originally meant to read and written by enlisted soldiers with little training. It was supposed to be written like "plain English". That's why there are "paragraphs". At my original job, one programmer took that to heart. He wrote the program like an English essay. On physical cards, one sentence followed another on the same physical card. He only went to a new card when the next word wouldn't fit. Maintaining that was a nightmare. This was before online editors.

  • @kyleareich
    @kyleareich Před rokem +1

    Dave, I love your videos man. You’ve got a real talent for explaining this kind of stuff in a way that’s easy/clear to understand.

  • @75slaine
    @75slaine Před rokem

    Nice walkthrough Dave. Vector is a very powerful structure. I recently created a C implementation for a hobby project I'm working on for my Amiga 500, used LLVM on my Mac to test it thoroughly for RAM safety issues first. I wasn't aware of the unique_ptr capability as I never really made the leap fully into C++, I was definitely the C+Classes kind of dev. 👍

  • @3rdman99
    @3rdman99 Před rokem +8

    Since the video is about "modern" C++, a couple of code-review pointers..
    1) Line 9-15: You should use "enum class" instead of "enum". The former (available from C++11) will avoid name-collisions.
    2) Line 86: You don't need to insert a space between two ">"s like "> >". You can just write ">>" since C++11.

    • @DavesGarage
      @DavesGarage  Před rokem +7

      clang complains if you don't space out the angle brackets. I just don't like warnings in my code, and don't believe in disabling warnings, so I added the space...

  • @raymundhofmann7661
    @raymundhofmann7661 Před rokem +3

    Even though this is C++ 11, released 2011, what makes this possible was from the beginning in the C++ language: constructors and destructors tied to scope, simulating value semantics. So the std lib gives modernized concepts building on that. One crucial thing for the language was move semantics also added with c++ 11 to conveniently handle moving objects between scopes, for objects that need to be unique, not copyable.

    • @GamersUniverseOE
      @GamersUniverseOE Před 10 měsíci

      Actually, move semantics were not added, it was rvalue references that were added and move is just a nice side effect of this feature.

    • @raymundhofmann7661
      @raymundhofmann7661 Před 10 měsíci

      @@GamersUniverseOE Rvalue references wouldn't have much purpose without move semantics, or?

  • @TheDecguy
    @TheDecguy Před rokem +2

    I’m enjoying the elementary code snippets. It helps as I start learning. I’m an old FORTRAN guy so it’s takes me a while to get going in the right direction. Thanks.

    • @davidblake8612
      @davidblake8612 Před rokem

      Ah Fortran. I used to code in that too. It's actually not a bad language at all.

  • @SwapChain
    @SwapChain Před 8 měsíci

    Thanks for the super explanation. I hope this playlist gets more videos. It is very exciting to learn from someone who has been involved with the technology for so many years.

  • @scriptguru4669
    @scriptguru4669 Před rokem +3

    Thanks Dave, I'm pretty bad with c++, C fundamentals I'm not bad but I end up reinventing the wheel, I sort of have to how I learn and I really only make .dlls to interact with an API [dj program] The only stuff that "sticks" is the stuff I use.
    I'm internet taught, so I've gaps, and I really don't know best practice, it works or it doesn't.
    vectors I'm down with, you're right about the name [writing xml from raw data made me face the fear, the API uses c_strings for the speed]
    mt19937, I've used that before too.
    I recently made a d3d11 thing and my API tutors recommended CComPtr, every d3d11 tutorial uses ComPtr, confusing and frustrating for somebody who barely uses normal pointers, But I got there in the end [rendered cat.png with alpha]
    Content like this I really enjoy thanks [that said I don't think you've made a bad video yet]

  • @sirflimflam
    @sirflimflam Před rokem +13

    I've been really wanting to get back into C++. I diverted to C# back in a time where conventional wisdom told you to actually avoid the C++ standard libraries (a long, *long* time ago). But much like how C# isn't anything like it was when I first started learning it (remember when they championed verbosity?) c++ feels like a completely different beast now.

    • @davidblake8612
      @davidblake8612 Před rokem +1

      Yeah at one point MicroSoft basically crapped on C++ and championed C#. They tried to discourage the former and promote the latter. I'm guessing this is because C# was their answer to Java.

    • @karsh001
      @karsh001 Před rokem

      ​@@davidblake8612 C# is, or at least was Java. MS got to pay a pretty penny for that in the start of the milennium.

    • @davidblake8612
      @davidblake8612 Před rokem

      @@karsh001 What?

    • @karsh001
      @karsh001 Před rokem

      @@davidblake8612 google should take you there: settled of of court 2001 Sun Java Microsoft C# settlement.

    • @lazyh0rse
      @lazyh0rse Před rokem +1

      I learned both, and I choose c++ every single time. C# have evolved a lot, but it's still a pain in the ass to port to other platforms aside from windows. Not to mention, C++ is honestly not hard, I'm surprised how easy it's compared to java, your code can be short and fast just as high level languages.

  • @leafylotus
    @leafylotus Před rokem +2

    Hey Dave, these C++/C insights are friggin amazing. Thank you

  • @irbaboon1979
    @irbaboon1979 Před rokem +1

    Haven’t touched C/C++ in 25 years or so…still, when I see your content I somehow get itchy fingers to write code again; keep up the great content :)

  • @ghostlucian12
    @ghostlucian12 Před rokem +3

    Actually c++ std library has an std::array container which encapsulates a statically sized array, where std::vector container encapsulates a dynamically size array, also the capacity of the std:: vector with 1.5x the size of the vector length, when adding data to a std::vector and reaching the max size std vector reallocates the vector with 1.5x the size needed, for speed improvements, because heap allocations takes time(more than a simple copy of data)
    Besides unique pointers there is shared pointers(shared_ptr), shared pointers have the option to retain the same data through multiple objects of shared_ptr, to keep track of the data they use a reference counter, where it is increased when the object is shared with another shared_ptr object, and decreased when the shared_ptr object is deleted. Only when the reference counter reaches 0(the last shared_ptr was deleted) it will actually delete the data.
    Modern C++ has a lot of containers that help code C++ much easier and managed, the threading library was build preaty easy since c++ 11

    • @zemlidrakona2915
      @zemlidrakona2915 Před rokem

      IMO shard_ptr is terrible. It's twice the size of a regular pointer and locks you into thread safety and weak pointer overhead even if you don't need it. Programmers used to implement reference counting pointers all the time with much less overhead than std::shard_ptr

  • @NinjaRunningWild
    @NinjaRunningWild Před rokem +69

    Dave, can you do a video on exactly how Compatibility Mode works in Windows? I think that'd be fascinating to a lot of people.

    • @ProtossOP
      @ProtossOP Před rokem +6

      I second that, that’d be awesome.

    • @the_beefy1986
      @the_beefy1986 Před rokem +2

      I'm guessing the shell exec function has a bunch of "if {flag} then {adjust library path to use old library implementation}" statements.

    • @Starchaser38
      @Starchaser38 Před rokem +1

      Yes, I'd like to know, too!

    • @bfth121
      @bfth121 Před rokem

      @@the_beefy1986 Or the windows loader just simply replaces the references in the exec tables to the old required library functions on execution

    • @compscienthusiast
      @compscienthusiast Před rokem +1

      That would be a great video. I have heard from work colleagues that compatibility mode should use something like virtual hardware emulation to simulate the libraries used on older systems, but I can't recall exactly. Why some modern versions of Windows get less and less lightweight, since they have to pick up and move along with older libraries and functionality built in for legacy apps.

  • @gumbilicious1
    @gumbilicious1 Před rokem

    Excellent video, good distillation. I have been programming quite a bit of C at work which has made me curious about C++ again. I haven’t programmed C++ since college but I have heard that C++ has many more features than it used to. Unique pointers are def something I was interested in

    • @cyberchef8344
      @cyberchef8344 Před rokem

      Modern C++ (written correctly) is completely different from what you probably learned in college. When I was in college the only aspects of C++ they really covered were basic classes and polymorphism. There was nothing about templates, move semantics, smart pointers, etc...

  • @colinmaharaj
    @colinmaharaj Před rokem +2

    So many years ago, because I was a bad c++ programmer, I wrote an app to find the match between my new and delete and my new[] and delete [].
    If I could not find the corresponding deletes, then I had a leak. If I used the memory after a delete then I had an access violation. My coding is not very sophisticated so my errors may not be very sophisticated,
    But the utility I wrote still works pretty good for me.

  • @disruptive_innovator
    @disruptive_innovator Před rokem +4

    I took a long journey away from C++ and haven't looked back, but this gets me interested in poking around once again. Thanks Dave.

  • @k34561
    @k34561 Před rokem +5

    I love the STL library. I tell people there is two era's in C++ Pre-STL and Post-STL. They are different. I have architected 3 major systems in the Mechanical CAD area. I started a big project using STL with shared pointers in ~2005. It was pre-C++ shared_ptr, so I developed my own. It basically solved all of the memory problems. I never switched to the std::shared_ptr because I liked my shared pointers better. They use an embedded count, uses one allocation instead of two. Also changing over a million lines of code to std::shared_ptr would be a pain.
    -Kurt

    • @maleldil1
      @maleldil1 Před rokem

      It depends on what you call STL. C++98 had a standard library with containers and algorithms, but I'd hardly say a second era of C++ started back then. C+11 was a bigger change, with the introduction of move semantics, smart pointers and type inference.
      Regarding your own shared pointer vs std's: after C++11, did you modify your pointer to use move semantics? If not, you're missing out on an optimisation: using std::move on a std::shared_pointer allows you to move the object without increasing and immediately decreasing the reference count.

    • @NoNameAtAll2
      @NoNameAtAll2 Před rokem

      shared ptrs created via make_shared do only 1 allocation

    • @NoNameAtAll2
      @NoNameAtAll2 Před rokem

      how does embedded count work?

    • @pavelperina7629
      @pavelperina7629 Před rokem

      shared_ptr contains number of strong and weak references and mutex. They use inplace new operator when they are created using make_shared so both control structure and data are created in one allocation, but it has one side effect: memory is not freed as long as anyone holds even weak reference to data. If you create shared_ptr from pointer, data are freed when number of strong references reaches zero.

  • @douglascaskey7302
    @douglascaskey7302 Před rokem +2

    Just as a note for those that use the Qt framework.... you can use the QScopedPointer and QSharedPointer classes instead of the std unique and shared points repsectively. Also Qt provides the QVector class to handle vector operations.

  • @jrkorman
    @jrkorman Před rokem +2

    Nice little review. Haven't really touched C/C++ in quite a number of years.

  • @velho6298
    @velho6298 Před rokem +6

    I think one of the most important features from the C++11 was the move operation.

    • @irisaacsni
      @irisaacsni Před rokem +1

      It was a nice addition because of semantics, but it also made the language considerably more complex which makes me question if it was worth. After all, you could just define a move() function since C++98. C++ would be much better with destructive moves but it is impossible to change now.

    • @oracleoftroy
      @oracleoftroy Před rokem

      Yeah, I think move is the single most important addition in C++11 and is still probably one of the most important features of all modern C++. I was most excited for lambda, but once I played with move, I realized it solved a lot of design problems as many types don't have a natural copy and introducing reference counting or similar to allow the type to work in containers felt like a hack. A lot of types are very naturally move only and finally being able to express it avoids a lot of the complexity of trying to work around not having it.

  • @davelaverie1799
    @davelaverie1799 Před rokem +3

    Great to see the return of the Friendly Giant. I missed him.

  • @enochabban9454
    @enochabban9454 Před rokem

    The blurred background is amazing. Makes me want to stay glued to the video.

  • @harshitjoshi3082
    @harshitjoshi3082 Před rokem +2

    I definitely would have more videos about c++ intermediate topics, absolutely love the content! Thanks for making this

  • @vasiliosmagriplis
    @vasiliosmagriplis Před rokem +5

    Great video. I'm often surprised by the amount of coders who seem to be unaware that modern idiomatic C++ avoids many of the pitfalls of C. I've been using C++ both professionally and in personal projects now for years -- with RAII, the standard library, and move semantics, I find I almost never have to directly use dynamic memory, new() or malloc() or worry about memory leaks. The few times I ever need dynamic memory (e.g. for dynamic/virtual dispatch), std::shared_ptr or std::unique_ptr suffice, and if I need a chunk of memory (e.g. to pass into a native win32 function), a std::vector suffices.

    • @BobSmun
      @BobSmun Před rokem +3

      Modern idiomatic C++ even avoids several pitfalls of old idiomatic C++

    • @realpainediaz7473
      @realpainediaz7473 Před rokem +1

      @@ABaumstumpf "i think it is understandable that people still fall for those things cause many universities and programming courses still do it backwards and start with C first, and then go with old C++ and only at the end even tell you that there are better ways."
      🙀😵😱

  • @joemccay9978
    @joemccay9978 Před rokem +42

    You need to be careful with Vector like containers. If you are going to add a lot of objects, you need to make sure that you allocate a size big enough to avoid growing the memory internally. The memory internally is usually implemented with arrays. When it needs to grow, it allocates a new array according to some internal metric. Then it copies the contents of the old array to the new array. This isn't usually a problem if you're adding 52 cards, but if you're adding a 1,000,000+ objects, you can take a performance hit.

    • @fluffycritter
      @fluffycritter Před rokem +10

      Yep, vector::reserve is a huge performance optimization. Also for very large or dynamically growing/shrinking arrays (especially when used as a queue) you probably want to use a std::deque instead.

    • @mogenshansen7210
      @mogenshansen7210 Před rokem

      Right.
      If you know in advance how many element the vectoe is going to contain, call std::vector::reserve to avoid reallocation.
      Having said that, moving std::unique_ptr's from one memory area to another during reallocation is fairly cheap and independent of the complexity of the object being managed. But of course it is a performance hit compared to not moving a 1'000'000+ std::unique_ptr's

    • @miroslavmikus6480
      @miroslavmikus6480 Před rokem

      @@fluffycritter Yes, definitely use dequeue, if you are only adding new elements on begin/end or removing them from begin/end. But if you are searching for insert point and then inserting it then cache prediction / cache misses can mess up everything :D The vector gotten slower than list/dequeue when the elements were about 104B and more. But with smaller elements that lookup for the insertion point got massive advantage by being stored sequentially in memory instead of jumping randomly everywhere and having cache misses for almost every step...

    • @DavesGarage
      @DavesGarage  Před rokem +5

      That, or look at the generated code, and sometimes its obvious from that. But yes, don't fix things that aren't causing actual problems.

    • @sneezingfrog
      @sneezingfrog Před rokem +5

      @@andrewholden1501 I find that with the caches on modern hardware, what used to be the most optimal data structure, say, 30 years ago is more often than not handily beaten by a vector just due to cache involvement. It's a bit saddening, given the elegance of some of the other approaches, but the profiler results are what they are.

  • @leosthrivwithautism
    @leosthrivwithautism Před rokem +1

    Dave I don't know if you'll see this but my Friend I wanted to thank you. First you have an amazing audience base. This comment is outside of the scope of the video, sorry about that. But still it wasn't till I discovered your channel a while back and found you were autistic that It motivated me enough to start my own channel. I scared but a few of your viewers supported me and one was even kind enough to give me my first subscriber to help push me forward in my channel creation. I wouldn't of had a channel if it wasn't for your supportive audience. And I got no one else other than you as well for being an inspiration. Now unfortunately my channel has been sputtering and has really gain much traction but that's my fault. I had no idea how youtube worked and never created a video in my life. But I'm planning an overhaul to get things going again. Thank you so much for such an amazing channel. For the inspiration and thank you to anyone reading this for being supportive to a man who used to be scared of his own shadow and thanks to you found his voice. Sorry for the long comment but I just felt a need to send a big thank you to everyone. 👍

  • @Gattancha
    @Gattancha Před rokem

    Only just trying to get my head round C++ and your videos are great at trying to understand it all

  • @IanJohnstonblog
    @IanJohnstonblog Před rokem +4

    Very good synopsis… I still get hit in my childhood feels with the friendly giant ending. The CBC overlay is also a nice touch. :)

  • @Gastell0
    @Gastell0 Před rokem +6

    That's a really helpful video, I absolutely love the description of "C with Classes", this perfectly describes the pitfall I have fallen into myself!

    • @rightwingsafetysquad9872
      @rightwingsafetysquad9872 Před rokem +1

      There used to be a language called C With Classes. The original C++ was effectively C With Classes 2.0

    • @toby9999
      @toby9999 Před rokem +2

      I'm also one of those people who do "C with classes" programming. Probably because I was a C developer. That said, I do use the STL containers and iterators etc, but none of the new stuff. Interestingly though, C++ was originally "C with classes" conceptually, according to Stroustrup.

    • @wuxxy
      @wuxxy Před rokem +1

      @@rightwingsafetysquad9872 C++ was originally called C with classes until it was renamed to C++

    • @zemlidrakona2915
      @zemlidrakona2915 Před rokem

      "C with Classes" is a BS name in this context. C++ was called "C with Classes" before it was called C++. But it's been C++ since the 80s. So calling the pre C++11 langues as "C with Classes" makes no sense.

    • @rightwingsafetysquad9872
      @rightwingsafetysquad9872 Před rokem

      @@zemlidrakona2915 C With Classes was around for 4 years and saw very little adoption. It became C++ in 1982 with the addition of virtual functions, operator overloading, references, constants, and type-safe free-store memory allocation (new/delete). C++ caught on very quickly.
      A lot of people still write C++ as if it were C, but also has classes. Hence saying they write as if it were "just C with classes".

  • @akaalkripal5724
    @akaalkripal5724 Před 11 měsíci +1

    I'm back to C++ after 20 years thanks to Dave - in between, I visited the Python, Java, Rust, Julia, Typescript, Haskell and Lisp lands. C++ is like old wine - the older the better. Excited about C++ and WASM (another area where Rust has mindshare), Mojo and Zig.

  • @The_Gray_Zone_Man
    @The_Gray_Zone_Man Před 4 měsíci

    Thank you so much for the effort 👍, you already made my day . We are looking forward for more into this valuable in-depth technical stuff.

  • @ze_rubenator
    @ze_rubenator Před rokem +8

    std::move() is a whole can of worms 😄
    What it actually does is it returns an r-value reference to whatever you pass into it (the moved-from object), which in turn calls the move assignment operator (or move constructor) of the object being assigned to (the moved-to object).
    A lot of people use it wrong and think it deletes or deconstructs the moved-from object, but as you correctly pointed out this is not the case. You'll still have a leftover moved-from object, in some state, that you have to deal with.
    In fact just passing an object to std::move() and discarding the return value does exactly... nothing.

    • @anon1963
      @anon1963 Před 7 měsíci

      I picked it up in couple of hours, not that hard to be honest

  • @cablekiller
    @cablekiller Před rokem +3

    love the coding content. keep em coming

  • @henryjimenez4710
    @henryjimenez4710 Před 5 měsíci

    Great video, thank you very much. You have the best explanations of code i've ever seen on the web.

  • @davidstewart4228
    @davidstewart4228 Před rokem

    Nice to see a good practise for C++ introduced early in the learning process. I spent years fighting in the way described in the introduction. I give c++ another go.

  • @bertblankenstein3738
    @bertblankenstein3738 Před rokem +9

    Good info for sure. There is no doubt that C++ code allows for better memory management over C and these tools expand on that. Still, the programmer should be taking steps to keep things tidy. I'm a hobbyist and usually find myself debugging things where I am rotating or swapping elements in an array.

    • @sledgex9
      @sledgex9 Před rokem +3

      "debugging things where I am rotating or swapping elements in an array" -> There's a high probability that the STL already has some function that covers whatever you are trying to do yourself. You should familiarize yourself with what the STL provides. I recommend starting with the "algorithms" section of the STL.

    • @isodoubIet
      @isodoubIet Před rokem

      "I'm a hobbyist and usually find myself debugging things where I am rotating or swapping elements in an array."
      That's a rotate.

  • @ze_rubenator
    @ze_rubenator Před rokem +6

    A couple of things which are mentioned in the Core Guidelines concerning enums:
    1. Use enum classes, not enums. Enum classes have the advantage of being type safe, and are not implicitly comparable/convertible ints or other enums. This can help a great deal to alleviate stupid but hard to find bugs.
    2. This is more of a style preference thing, but still. Don't use all caps for enum elements. Partly to differentiate them from macros, and partly because it's annoying to read and write.

  • @2teaspoon
    @2teaspoon Před rokem

    I have just started learning C++ (a week ago) from a paid Udemy Course. I was introduced to vectors and yet to reach the pointers section.
    Your explaination is so clear, I was easily and instantly able to understand through unique pointers based on how you explained. Same quality as the paid course I am learning. Thank you very much for sharing your knowledge and expertise and completely free on this platform.
    I know there is a lot for me to learn, but I really appreciate how easy it was to understand this concept from you, How I should use these modern features from the start to tackle the very problems you stated in the video like memory allocation, heap corruption and other problems which may likely make me quit the language.
    But now I know your channel and the importance of learning the modern concepts thats gonna keep my fire to learn C++ and more imporatantly to know having a better expertise at writing better code will avoid most of hectic problems.

    • @cyberchef8344
      @cyberchef8344 Před rokem +1

      If you're just learning you shouldn't skip raw pointers. I can't speak for the creator of the video, but I would assume when he says 'never use new, delete, malloc, free, etc...' he means in production code you are writing from scratch. You absolutely should learn to use them, and anyone that says otherwise is incorrect simply because you will, at some point in your career, need to work with other people's code, and you can't just throw your hands up in the air if you need to find a heap corruption because someone else didn't use a smart pointer. There will also be instances where you may need to integrate with an api that takes raw pointers as parameters (more common than you think) and it's not a great idea to mix smart pointers and raw pointers.

    • @cyberchef8344
      @cyberchef8344 Před rokem +1

      Honestly a good rule of thumb: if you are able to write your own version of the vector, smart pointers, and other standard template library features then you are ready to use them, but I'd stay away from them until that point (unless you're thrown into it in the workplace, in which case use modern stuff, but go back and learn the basics)

    • @2teaspoon
      @2teaspoon Před rokem

      ​@@cyberchef8344 Thank you very much to spend some of your time for mentoring.
      I will keep these rule of thumb in mind. It will be very difficult to write my own versions of the standard template library at this point, but yes I should expect workplaces to implement their own stuff for the use cases they would have.
      Having full control of the data structure would be really great and handy to optimize things for certain use cases. But yeah I will require a bit of experience and understand the underlying implementations before moving forward on making my own.

  • @adamploof3528
    @adamploof3528 Před rokem +2

    Really appreciate this one. I'd been interested in learning a lower level language recently just out of personal curiosity and debated whether to invest my time in Rust or C++. It's cool to hear your perspective that C++ already has robust ways of handling memory safety. Feels like that's a point that doesn't get said very often.

    • @epiicSpooky
      @epiicSpooky Před rokem +3

      It's still not as comprehensive as Rust. (but much better than what we did 20 years ago.)
      So even if you work in C++, it's worth spending time learning Rust. The mutability constraints ensure no problems with concurrency too, which is also important in modern code.

    • @cyberchef8344
      @cyberchef8344 Před rokem +2

      If you're trying to pick up a lower level language simply to learn low level concepts just use raw C. If you are trying to learn it for the above and so that you can possibly use it in the real world for somewhat high level applications do C++. If you want to learn a new language you can use on a lot of novel projects but also somewhat learn low level concepts, pick Rust

    • @nicwhites
      @nicwhites Před rokem +2

      IMO, learn both. Figure out what you are gonna use the languages for. I personally have been program C/C++ for years at different levels, but have gotten into rust this past year. I know I’m gonna get some hate, but Rust is a far better experience once you get past the difficulty of working with/against the compiler. I mean having a built in package manager and build system cannot be understated; both of those make Rust a much better experience. I know they have package managers for C/C++, but they are not native and far inferior.

  • @SKULDROPR
    @SKULDROPR Před rokem +3

    I've found that a lot of the older languages tend to have libraries like this that extend their functionality, so they have parity with more modern languages. It's a shame that they are often overlooked. I think that a lot of coders should at least spend a little bit of time with C or C++, even if it's just a few weeks, you'll learn a lot.

    • @karsh001
      @karsh001 Před rokem

      Standard template library isn't exactly new. It was included in the C++ standard in -94.

    • @SKULDROPR
      @SKULDROPR Před rokem

      I'm aware, I'm only said classes like vector get overlooked, like Dave said. Another good example would be array broadcasting in numpy. It's been around forever, since like '95. I still see people using loops. They get scared and stick with what they know.

  • @marksilverman
    @marksilverman Před rokem +4

    Smart pointers came out in 2011. Vectors have been around longer (1998?). Both really great features, but there are so many amazing changes since then!

    • @joelcorley3478
      @joelcorley3478 Před rokem +2

      I started using them when they came out as part of the C++ boost library before they were adopted by the std library.
      I also wrote my own version to use in kernel space. Less capable, of course as debugging templates was a PITA.

  • @sorbpen
    @sorbpen Před rokem

    Dave thank you so much.
    You said "vector is just a dynamic array".
    I have just spent the better half of a course trying to get my head around it and researching it, but no one put it in those words that just dispelled any lingering doubt of me not understanding exactly what I'm doing.
    Someone also described it as a drawer with folders, in that if you want to add something you add it at the start of the array and shove the rest of the files one step back in memory so to speak, thus side-stepping the need to copy the entire drawer into another location in memory before adding the new entry to it.
    Someone please correct my understanding but this is as best as I've understood it so far.

    • @scriptguru4669
      @scriptguru4669 Před rokem

      No you can do that with v.insert(v.begin(), 6) but it is inefficient, you don't make the moves but the moves do have to be made, it's more usual to .push_back() [add to the back of the list] with vectors. for add to front or back it's better to use std::deque it is similar to vectors.

  • @ebred76
    @ebred76 Před 11 měsíci

    Listening to you is like reading a condensed well written no fluff book, without the reading. Well done

  • @galbareket3995
    @galbareket3995 Před rokem +4

    I haven't touched c++ yet I was thinking of trying it after learning c, good tutorial. Vector is really an intimidating name for a dynamic array, I think that does names are really threatening for beginners in c++.

    • @snesmocha
      @snesmocha Před rokem +1

      reminder, it's just the mathmatical name of a linear group of numbers, it's probably a byproduct of bjorne being a mathematician.
      a single number is a scalar, an infinite countable sequence of numbers is a vector, 2 or more groups of numbers is a matrix, and so on.

    • @MrHaggyy
      @MrHaggyy Před rokem +1

      Not quite, in math a vector is a countable infinit number of objects with the same datatype. Which is a dynamic array of variable datatype. But i get why it sounds confusing if you only know algebra and geometric vector calculus.

    • @taragnor
      @taragnor Před rokem +1

      Yeah, bringing in technically mathematical terms can always get a bit confusing. I understand why they did it, since array and list are already taken in computer science. At least it's not Haskell and it's monads.

    • @snesmocha
      @snesmocha Před rokem

      ​@@taragnor 💀i don't get how anyone can tolerate Haskell. it's literally pure maths in programming fashion. i still have no idea how to use it, it just seems confusing for the sake of being confusing half the time to be honest.

    • @snesmocha
      @snesmocha Před rokem

      @@MrHaggyy ah, thank you, let me correct myself

  • @Bonta768
    @Bonta768 Před rokem +15

    Dave, I was using std::unique_ptr 15 years ago - it was very helpful. Rust is only the second high level language allowed in the Linux kernel in its 30 years. Microsoft has begun replacing parts of the Windows kernel with Rust code. Rust is the first of a new class of code languages - please dig deeper to understand why. C++ coders can learn Rust easily.

    • @MyAmazingUsername
      @MyAmazingUsername Před rokem +13

      Yep. Dave is never very knowledgeable about things. Like when he does programming benchmarks and looks at the per-thread scores instead of the total score thus making zig seem 2x faster than it really is. Rust won his own benchmarks and he didn't even realize it because he couldn't read.
      As for C++, just because you use smart pointers doesn't make it safe. There is still messy partial copies, partial moves, shared memory, etc. Still awful.

    • @allObeserving
      @allObeserving Před rokem +6

      Just because the Linux kernel is using Rust doesn't mean it's better than C++, not to mention the backlash that came from the community when this decision was made including Linus.
      Rust is just C wannabe with it's memory safety BS but then C++ exists which makes Rust obsolete. Rust is just another overrated generic language and no one in their right mind is going to replace their wildly adopted and standardized C / C++ codebase for a new unstable language because the alphabet mafia said it's better. Rust is only good for those who are just starting in low-level programming. Funny thing I've discovered is that most Rust diehard fans are failed C++ developers.
      If you really knew C++ you would know that memory safety is not a problem if you use the RAII paradigm. Also, I'm pretty sure that whole Windows thing was a bluff. Another thing, C++ developers do not need any reason to learn Rust because Rust doesn't offer something that C++ already doesn't have. The only advantage Rust has over C++ is it's universal build system and package manager unlike C++.

    • @allObeserving
      @allObeserving Před rokem +4

      ​@@MyAmazingUsername You clearly have no idea about C++.
      What is a partial copy and a partial move? Are you talking about move semantics because move semantics is a memory management feature not a memory safety feature.

    • @davidblake8612
      @davidblake8612 Před rokem +3

      @@MyAmazingUsername Gosh programmers are soooooo arrogant sometimes. "Dave is never very knowledgeable" - bwahahahahaha.

    • @OrangeShellGaming
      @OrangeShellGaming Před rokem +3

      @@davidblake8612 Rust coders are particularly infamous for their "holier than thou" attitude.

  • @kilaposhi
    @kilaposhi Před rokem +1

    Great video, clear explanations. I need more modern C++ examples like that!

  • @norszabo
    @norszabo Před rokem +4

    Dave, I really love your videos - the only thing that makes me sad to a certain extent is the vector - it is a sure fire way to spend most of your CPU time dealing with cache misses. I am sure you are aware that it is a pointer to a list of pointers. I might be old though. Maybe this does not matter for most programmers today. I deal with this kind of stuff all the time when working with high performance code.
    For what it is worth, I understand your goal - memory problems are an issue for sure.

    • @davidblake8612
      @davidblake8612 Před rokem

      So what's the better way to do it please?

    • @KohuGaly
      @KohuGaly Před rokem +1

      @@davidblake8612 One way it to implement the move constructor and unimplement the copy constructor for card itself. That way it forces move semantics the same way unique_ptr does, but without the extra indirection.

    • @stysner4580
      @stysner4580 Před rokem

      It probably depends. If you're working on any performance critical application memory layout should still be a top priority and as such indirection should be avoided, especially in arrays.

    • @DavesGarage
      @DavesGarage  Před rokem +1

      If you need to keep track of a set of elements, what are you suggesting is more efficient than an indexed set of pointers?

    • @stysner4580
      @stysner4580 Před rokem

      @@DavesGarage Moving the data to the vector?

  • @DavidRomigJr
    @DavidRomigJr Před rokem +3

    I know this stuff but still throughly enjoyed you stepping through it. There was a time before I became comfortable with STL where I programmed pretty much how you said.
    I disagree with that the vector class should be called the array class. STL has an array class that functions like a version of the C array but with useful helpers. I’d find it confusing at least if these got swapped around. :)

    • @cyberchef8344
      @cyberchef8344 Před rokem

      I had the same thought - though I do understand how vector can be a confusing name for those with a physics/math background. dynamicarray or something along those lines may have been a better choice.

  • @vinniciusrosa8284
    @vinniciusrosa8284 Před 4 měsíci

    Thank you. I like to watch your videos because you really know about the subjects you are talking to. I can here fortify my knowledge.

  • @SomeRandomPiggo
    @SomeRandomPiggo Před rokem

    Very good video! I have been using C for some small projects recently but now I see what modern C++ can do I'm quite surprised

  • @KoRNeRd
    @KoRNeRd Před rokem +3

    The point is you are not shooting yourself in the foot, because you know better. Many people do not. That is why Rust exists. Foot shooting should be an unsafe operation.

    • @bengraham3707
      @bengraham3707 Před rokem

      Right. Because Rust is the language for people who don’t know better…

    • @limitationsapply
      @limitationsapply Před rokem +2

      The point is more that every programmer is a fallible human. Even if you "know better", you're not immune to mistakes.

  • @Upliner1
    @Upliner1 Před rokem +3

    I use unique_ptr in my current project but sometimes I still encountered some issues with dangling references that Rust borrow checker could've catched at compile time. So I really have a hope to write my next project in Rust.

  • @nonlinearsound-001
    @nonlinearsound-001 Před rokem +1

    Dave, thanks for doing these! I have been coding in C++ a couple of years ago as a game developer and I would love some guidance on new and modern and especially clutter free and clear C++. Interesting to me would be: efficient data structure handling in c++, thread safe programming, efficient ways of using system APIs, especially the Windows style API and very interesting to me at least: How can I code maybe close to a coding style of Go maybe? (if that even makes sense but as I fell in live with Go I would like to use C++ in a similar way - a good mixture between function based structuring of your main application and logic enhanced structures just like classes but without inheritance - against to what I learned back then as a pure class based aproach without a lot of use of the c++ standard library data and control structures and a wild mix of instantiation and heavy usage of inheritance beyond unerstanding your own code eventually)

  • @Hipdudester
    @Hipdudester Před měsícem

    The Friendly Giant!!! You have just become my favorite C++ person. , Wow! great video learning a lot.

  • @maddsua
    @maddsua Před rokem +6

    Finally, someone on the entire Internet who actually knows about the STL. I was getting more and more annoyed by the "Rust cultists" lately, you probably know what I'm talking about. Thanks for the video!

  • @NoNameAtAll2
    @NoNameAtAll2 Před rokem +3

    ...new?
    aren't smart pointers a decade old?

  • @theo-dr2dz
    @theo-dr2dz Před 8 dny

    The at() function of vector has two nice features: first it does bounds checking: it throws an exception if the index is out of bounds. Second, it is const. So it can be called on a const vector, unlike the [] indexing operator.
    I think the best usecase of custom deleters on unique_ptr and shared_ptr is that it can be used for any thing that needs a close() style function. So you could make a unique_ptr to a file, where the custom deleter closes the file. Now it is impossible to forget closing the file: the deleter will do it automatically when the unique_ptr runs out of scope. This can also be done for database connections and anything that needs some kind of close function. It's a bit like the try with resources thingy of java, only done right.

  • @trnpsycho
    @trnpsycho Před rokem

    Who doesn't want to see more of Dave teaching code.???? I'm a long time programmer of various languages, and I'd still go through the entire catalogue if Dave were to release a C++ from beginner to winner program!

  • @AK-vx4dy
    @AK-vx4dy Před rokem +3

    I'm pretty lame on C++ but as i understand unique_ptr and shared_ptr have additonal cost and it is not "zeroed" by compiler or i'm wrong ?
    I'm also lame to Rust, but as i understand protections in Rust are forced in compile time so have no runtime cost also this philosophy
    allows Rust compiler to futher optimize than is allowed in C++ or C.
    Hype is really strong but i'm almost sure you underestimate Rust because even if i'm wrong on pointers and memory protection
    Rust also brings very powerfull type system wich can let you protect future programers from generating or even represting incorrect states
    also in compile time...

    • @leduyquang753
      @leduyquang753 Před rokem

      `std::unique_ptr` is a zero-cost abstraction, it does the same amount of work as if you were to `new` and `delete` yourself. `std::shared_ptr` has to do some bookkeeping and also keep itself thread-safe so yes it has costs, but there are few situations you will want to use it anyway.
      The default constructors of both initialize them to null.

    • @AK-vx4dy
      @AK-vx4dy Před rokem

      @@leduyquang753 I'm lame to C++ but as i know it is pointer to pointer so extra memory access. It can be heavily optimised, elided, inlined or maybe even converted to raw pointer, but not always because of many quirks in c++. Also some checks are done at runtime so some penalty is unavoidable or needs much care from programmer.
      Shared it is whole diffrent story and in this case it is hard to take clear win, as I understand Rust uses similar tricks with Rc, Arc.

    • @leduyquang753
      @leduyquang753 Před rokem +1

      @@AK-vx4dy `std::unique_ptr` is not a pointer to a pointer. And there is no runtime check.

    • @AK-vx4dy
      @AK-vx4dy Před rokem

      @@leduyquang753 it is pointer(or if you wish reference) to object wich contains (raw) pointer. if that definition fits you better, enjoy. From cpu side it is pointer to structure in memory wich contains another pointer to your data, so extra memory access (wich can be memoized in many cases or is already in cache if unique_ptr structure is on stack) is needed however you name it at higher abstraction level.
      So some penalty is unavoidable, maybe in many cases is neglible or small enough to pay it for security.
      Rust checks ownership and other rules at compile time, in C++ you can release raw pointer or invalidate unique_ptr value or move ownership from one unique_ptr to another, so some checks at runtime are unavoidable in some cases.
      Simply speaking its apples to oranges and unique_ptr clearly helps very much with safety but is no match to borrow checker.

    • @leduyquang753
      @leduyquang753 Před rokem +1

      @@AK-vx4dy That's a totally incorrect description of `std::unique_ptr`. It is a simple class with a pointer member to the object being managed, there is only one level of pointer.

  • @wertigon
    @wertigon Před rokem +3

    If you must use C++, do use these features, for sure. However, do also be aware that C++ is an unsafe language since it does not allow the enforcement of these features at compile time level. Sure, your code might be great but your compiled dlls might not. This means you can only be 90% sure there will be no memory leaks - using Rust OTOH, you can be 99% sure.

  • @nextlifeonearth
    @nextlifeonearth Před rokem +1

    Embedded (safety critical) software engineer here. Simply for simplicity and runtime I wouldn't write it like this.
    I'd just use an std::array if I already knew what length the deck is, which we do.
    And a card is two enum values, don't need heap for that (and the address can move for all I care, even if it didn't use the array, moving the value can invalidate the card with an extra field or enum entry).
    All cards need only be initialised once, they can be moved with std::swap (implement move constructor to invalidate the previous card)
    Heap is evil. (not really, but you may get where I'm coming from)

  • @GaryLuckenbaugh-xu8lr

    Dave, This is an exciting video. I see C++ in an entirely new light. Thank you so much!!

  • @stysner4580
    @stysner4580 Před rokem +5

    I might be biased but this just looks like janky, Rust like behavior in a still bloated and unsafe language... Everything registers like "oh so how Rust does it but worse" to me.

    • @AshishSinghh
      @AshishSinghh Před 7 měsíci

      I don't think rust will ever replace cpp ever. Cpp will be much improved in few years. Plus big corporation like car manufacturing partner charges millions just to switch from 2011 cpp to 2017 cpp. Imagine asking them to switch to rust. So its not just about how good rust is (which I don't like anyway) but also alot of library support etc

    • @stysner4580
      @stysner4580 Před 7 měsíci

      @@AshishSinghh well... Microsoft and Linux disagree with you... don't underestimate the cost of unsafe code in bot dev time and potential bugs.

  • @agdevoq
    @agdevoq Před rokem +4

    Rust: it protects you from yourself.
    C++: you must protect from the language itself.
    The fact that they designed a whole library to get around even the most basic issues of memory management, already speaks a lot.
    Listen, C++ has been my first language, and I was deeply in love with it. I mastered many advanced books from head to tail. I delved into the bottomless pits of template metaprogramming, hardcore operator overloading, and the likes. C++ gives you great power, but :)
    If you need execution speed, I think C++ is still the best out there.
    But most of the time you need DEVELOPMENT speed, and also out-of-the-box reliability and readability. And C++ can't compete there. I had to admit it to myself, a C++ fanboy, more than 20 years ago...

  • @TheExcellentVideoChannel

    Nice work Dave. Much appreciate this kind of content.

  • @darrennew8211
    @darrennew8211 Před rokem +2

    While it's possible to be as safe as Rust while using C++, C++ is still unsafe by default while Rust is safe by default. It's not impossible to have a second pointer to a unique_ptr content, for example: all you need is for it to be pointing to a function that can "return this;" Just like in the constructor for Deck, you iterate over integers that you then cast to the enum, rather than actually iterating over the enum itself. C++ is still a half-ass pile of kludges on top of a pile of sand. That said, knowing how to get as close as possible is helpful.

  • @muhdiversity7409
    @muhdiversity7409 Před rokem +3

    Hi Dave! Oh, and first :)

  • @cookoo4lyf
    @cookoo4lyf Před rokem +32

    Dave, I get the feeling you think rust is solving a problem that doesn't exist or that can be solved in other languages like c++ by just "using the right tools", but I promise thinking like that is missing the point of rust. If you have the time, I would really recommend really learning it, reading "the rust book" and following along with it, writing and building the examples, its not that long even. Part of the problem is if you write rust code like a c++ developer the language is awful, you have to learn not just the language but the idiomatic ways of doing things to really start to see the benefits of rust. Love the vids

    • @BobSmun
      @BobSmun Před rokem +18

      The point of rust is not missed. It is solving real problems, by making it much harder to shoot yourself in the foot
      But just because you can shoot yourself in the foot with c++, doesn't mean you have to. In the same way that you say that writing rust like c++ is bad, writing c++ like c is bad. Heck, c++ has developed so much in the last decade or so, that writing c++ like 'old' c++ is also bad. That is to say that the idiomatic ways of doing things changes over time. By using current recommended programming practices and guidelines, you can also achieve good and safe code. Yes, it is easier to deviate than rust - as c++ is less enforced and there is a whole lot more legacy to deal with - but it can be done and using the right tools does ease the effort
      With that, one of the bigger benefits of rust over c++ is less meaningful, in practice, than the hype around rust would suggest. That is not to say that rust isn't 'better', but rather that c++ gets a bad reputation for what mostly amounts to outdated usage practices

    • @lazyh0rse
      @lazyh0rse Před rokem +3

      I want to learn rust, seems promising. But I chose c++ because I think there are more beginner videos for c++ than rust. Maybe I'm biased, but I thought once I got to know how c++ works I'm excited to learn rust, so I know where does c++ misses the mark. But with my limited use of c++ I'm kind of satisfied with the language. I have used C#, javascript, java, all of which were really awful. C++ was actually quite good surprisingly, so I don't really get where the hate comes from. But I'm still learning so I could be too noob to know that already. Anyway, good comment, I would definitely learn rust eventually...

    • @scififan698
      @scififan698 Před 9 měsíci

      ​@@lazyh0rseif you found C# a worse language than C++, then you clearly missed something. I've been using both since their inception, and I can give you a million practical as well as theoretical reasons why C# is by far the better language construct. Even in terms of speed, because think of this fact: a compiled language pins down its processor code when it gets shipped as an executable, while a Jit compiled language can adjust and even optimize to the platform it runs on, giving it a future chance to exploit future processor instructions, environmental possibilities etc. far beyond what a precompiled executable can ever do. That, and many more better choices were made in C#. Now, mind you, I use both and many other languages each day, and they all have their place and strengths, but from most perspectives, C# is definitely the better language objectively.

    • @anon1963
      @anon1963 Před 7 měsíci +2

      ​@@scififan698C# is definitely not better lmao you ate wrong mushrooms

  • @k.alipardhan6957
    @k.alipardhan6957 Před měsícem

    Thank you!
    As an experianced dev, this video was the exact level I wanted; You don't over explain and move fast

  • @johnburgess2084
    @johnburgess2084 Před rokem

    I loved this explanation and tutorial; please continue with this series!

  • @johndowson1852
    @johndowson1852 Před rokem +3

    If you want to write safe modern code, you should not be doing it in c++.
    No matter how many optional safety features the committee adds, they will never be able to reduce the chance of footgunning anywhere even near the level of what actually modern languages offer. (cough, rust, cough)

    • @DavesGarage
      @DavesGarage  Před rokem

      If you shoot yourself in the foot, don't blame the holster, blame the operator, I figure!

    • @cookie04
      @cookie04 Před rokem

      @@DavesGarage I disagree.
      C++ may be memory safe if you do all the right things but Rust is memory safe by default.
      You can not invoke UB in Rust without the use of an unsafe block and there is a culture around them that encourages you to minimize your use of them and properly document the cases where it's actually necessary. In C there is potential for UB in every line.
      There is this notion that a good programmer can write bug free code 100% of the time. That's simply not true. Programmers are humans and humans make mistakes, no matter how good they are.
      A language should attempt to minimize the damage such bugs can cause. In C such a bug can lead to UB, which is a license to kill to the optimizer and allows it do basically anything.
      The best case is a compiler error notifying you before your code can even hit production. Rust optimizes towards making as many bugs as possible compiler errors instead of runtime errors.
      A good example would be attempting to access an array with known size at compile time out of bounds. In Rust that's a compile time error. In C that's a compiler warning and UB.
      If you use a Vec you don't get a compile time error but instead your code panics. But a panic is not UB. There is no chance that your program keeps chugging along with the wrong value.
      You can probably get a lot of that with C++ too but my point is that you have to put in extra work and that it is more difficult.
      In Rust you get that by default.

  • @iincognito96
    @iincognito96 Před rokem +9

    idk why people hype up rust so much they probably dont know any c++

    • @TheFreeSpiritKID
      @TheFreeSpiritKID Před rokem +1

      Well it's typesafe, simple and blazingly fast

    • @NinjaRunningWild
      @NinjaRunningWild Před rokem +7

      It's just the new hotness right now. Has some nice features that avoid a bunch of the pitfalls of C++. But, really it’s just kicking the can down the road. Never underestimate people's want to avoid rolling up their sleeves & doing hard work by having potentially magical fairy dust on the horizon that "will cure all ills" with zero negative repercussions ever aka "chasing the dragon".

    • @zf4hp24
      @zf4hp24 Před rokem +1

      Just "const" everything in C++. Done.

    • @us07251
      @us07251 Před rokem +2

      In most languages, programmers have to catch errors intentionally. In Rust, programmers have to ignore errors intentionally.
      I like the Rust approach, because it reminds me to deal with errors ahead of time or ignore them if I want.

    • @Bonta768
      @Bonta768 Před rokem +1

      @@NinjaRunningWild Nope. Rust only exists because of a lot of hard work trying a new approach.

  • @stepannovotny4291
    @stepannovotny4291 Před rokem

    I enjoy your recent videos such as this one, which are of interest to people learning embedded programming.

    • @DavesGarage
      @DavesGarage  Před rokem +1

      Thanks, I'll keep trying to do more and see if I can build an audience!

  • @ultraenergy313
    @ultraenergy313 Před rokem

    Thank you for making this simpler to understand

  • @AbelShields
    @AbelShields Před rokem +6

    "modern C++ stl has essentially the same protections (as Rust)" - sorry, but that's complete BS. Lemme know when your compiler warns about invalidating references due to modifying a container inside a loop. Or what about a dangling reference, you take a reference to something in the container and then it gets resized. Silent, critical failures.

    • @DavesGarage
      @DavesGarage  Před rokem +4

      Show the the C++ code that does it and I'll show you where it's the programmer's fault for abusing the language, not the language's fault for not enforcing safety on the user. Use the tool properly, it will treat you well.

    • @AbelShields
      @AbelShields Před rokem +1

      @@DavesGarage it's all well and good to say "it's the users fault for misusing it", but unfortunately that won't prevent any bugs. I'd love to be able to say "memory safety bugs? Just think about it and don't program any!", but unfortunately it's not that simple. If the language allows users to make bugs, then there will sometimes be bugs, whether due to negligence or oversight. The language can be designed to eliminate certain bugs - you'll never get a use-after-free in Python - but saying the STL has the same protections as Rust is just unequivocally wrong. If you try to write a bug concerning references outliving owners in Rust, it's impossible (in safe Rust). Whereas in C++, it will compile perfectly fine and perhaps not even be warned about by the compiler or even static analysis. You can say "that's misuse of the language", and perhaps it is, but *that still doesn't stop the bugs!*

    • @MoeFH
      @MoeFH Před rokem +2

      @@DavesGarage Dave, it's very strange reading this comment after watching this video. What you wrote here could also be used to dismiss the whole video: there's no need for unique_ptr or any other modern C++ stuff; "C with classes" with manual pointer management is perfectly fine, and if the code has dangling pointers, use-after-free errors or any other number of memory bugs, that's just the programmer's fault for doing things wrong and not a problem with the language.

    • @OriginalJetForMe
      @OriginalJetForMe Před 6 měsíci

      @@DavesGarageby that logic you should just code in assembly. The tools are there to make your life easier, and one of the ways modern languages do that is by helping to protect against what you call “abuse.”

    • @user-og4fk6os1r
      @user-og4fk6os1r Před 3 měsíci

      These do not lead to memory corruption which is what causes vulnerabilities and BSODs. That's his point, not that it solves every conceivable problem. If you want a language that will hold your hand and coddle you then use VB.

  • @PretzelPup
    @PretzelPup Před rokem +1

    @1:20 you were going to tell us how to stop calling malloc, and I got excited. Currently working on an ESP32 project using I2S, and since it's a DMA transfer, I have to call malloc(size) and pass that to I2S. I'm having issues with the memory sharing between the two cores, with one core getting the data, the other core running and displaying an FFT on that data. No worries, I'll figure it out, but I would have liked a better way to get memory. Thanks for a great topic!

    • @oracleoftroy
      @oracleoftroy Před rokem +1

      If your I2S code is expecting to take ownership of the memory and call free() on it, nothing wrong with mallocing the memory.
      If you need a buffer and don't mind it being value initialized, std::vector(size) is fine. It does take up three pointers worth of stack space which might be a concerned on a constrained system, but it is pretty easy to use.
      You might want to look into std::make_unique(size) or std::make_unique_for_overwrite(size) for a more lightweight version if you aren't resizing. Both will give you a single pointer with no extra overhead, and the 'overwrite' version will default initialize (leaving whatever junk was in memory) whereas the other will value initialize (call the default constructor or zero the memory).
      Of course, if you know at compile time how big a buffer you need, std::array (especially post C++17) is great. No dynamic memory allocation, but you do need the available stack space.

  • @vhm14u2c
    @vhm14u2c Před rokem

    Thanks for posting this Dave. I seen coding you done earlier with fastLED where you included vector.h to use a time function. I was thinking the vector library was a graphics library, hence the name, vector.

  • @marrtins
    @marrtins Před rokem +1

    Please more programming videos including stories about programming from you carrier - serious or funny ones! Thanks for the content! It's great!

  • @ManInTheAttic57
    @ManInTheAttic57 Před rokem

    Great example and explanation. Thank you.