Modern C++: Unique Ptrs and Vectors

  Рет қаралды 131,833

Dave's Garage

Dave's Garage

Күн бұрын

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

Пікірлер: 973
@CristiNeagu
@CristiNeagu Жыл бұрын
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 Жыл бұрын
Yep, me too
@CristiNeagu
@CristiNeagu Жыл бұрын
@@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 Жыл бұрын
@@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 Жыл бұрын
I am also interested in more videos like this. It would be really cool to know how these methods change performance?
@forbiddenera
@forbiddenera Жыл бұрын
Agree! My cpp is weak these days
@bdp-racing
@bdp-racing Жыл бұрын
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 Жыл бұрын
Hear hear...
@sorbpen
@sorbpen Жыл бұрын
@@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 Жыл бұрын
school level teaches what algorithm is, not how to program with memory control...
@TheInevitableHulk
@TheInevitableHulk Жыл бұрын
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 10 ай бұрын
You can thank your school teacher for your ability yo understand this more advanced lesson.
@snobaste
@snobaste 8 ай бұрын
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!
@nicholasdark1270
@nicholasdark1270 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
Imagine how I, a VB6 programmer, feels ...
@ForaPhil
@ForaPhil Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
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.
@poushankumarbiswas8693
@poushankumarbiswas8693 10 ай бұрын
Sir, you should now really start considering teaching here on KZfaq. 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 Жыл бұрын
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.
@brycesharp1796
@brycesharp1796 Жыл бұрын
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.
@scienceandmathHandle
@scienceandmathHandle Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
wouldn't this need to reallocate? or does it just trim?
@JATmatic
@JATmatic Жыл бұрын
@@julienmarcuse9023 It might do reallocation, it is implementation defined. Depends likely how much excess capacity the vector has.
@denkalenichenko4124
@denkalenichenko4124 Жыл бұрын
​@@JATmaticIm not sure, but C++ doesn't have own reallocate. Only C realloc
@zeez7777
@zeez7777 Жыл бұрын
@@denkalenichenko4124 Yes so that is still c++, its a superset of C
@rickpoeling6831
@rickpoeling6831 Жыл бұрын
Excellent working example. Your coding style is extremely efficient and easily understood.
@KeithCooper-Albuquerque
@KeithCooper-Albuquerque Жыл бұрын
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!
@DogeOfWar
@DogeOfWar Жыл бұрын
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!
@kebien6020
@kebien6020 Жыл бұрын
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 KZfaq: `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 Ай бұрын
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.
@HyperFirezAlt
@HyperFirezAlt Жыл бұрын
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!
@zactron1997
@zactron1997 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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"`.
@mogenshansen7210
@mogenshansen7210 Жыл бұрын
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 Жыл бұрын
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 🇮🇪
@DavesGarage
@DavesGarage Жыл бұрын
Thanks, I appreciate you saying so!
@TractorWrangler01
@TractorWrangler01 Жыл бұрын
You are an excellent teacher Dave.
@delsorou8279
@delsorou8279 Жыл бұрын
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.
@leafylotus
@leafylotus Жыл бұрын
Hey Dave, these C++/C insights are friggin amazing. Thank you
@SwapChain
@SwapChain 8 ай бұрын
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.
@TheBowlingPotato
@TheBowlingPotato Жыл бұрын
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 Жыл бұрын
> 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 Жыл бұрын
That sounds perfectly useless. Why handicap yourself like that?
@3rdman99
@3rdman99 Жыл бұрын
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 Жыл бұрын
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...
@kyleareich
@kyleareich Жыл бұрын
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.
@DavesGarage
@DavesGarage Жыл бұрын
Thanks, I appreciate that!
@TheDecguy
@TheDecguy Жыл бұрын
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 Жыл бұрын
Ah Fortran. I used to code in that too. It's actually not a bad language at all.
@johnmckown1267
@johnmckown1267 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
@@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.
@midge9740
@midge9740 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
@@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.
@douglascaskey7302
@douglascaskey7302 Жыл бұрын
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.
@colinmaharaj
@colinmaharaj Жыл бұрын
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.
@scriptguru4669
@scriptguru4669 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
​@@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 Жыл бұрын
@@karsh001 What?
@karsh001
@karsh001 Жыл бұрын
@@davidblake8612 google should take you there: settled of of court 2001 Sun Java Microsoft C# settlement.
@lazyh0rse
@lazyh0rse Жыл бұрын
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.
@kilaposhi
@kilaposhi Жыл бұрын
Great video, clear explanations. I need more modern C++ examples like that!
@theo-dr2dz
@theo-dr2dz 7 күн бұрын
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.
@disruptive_innovator
@disruptive_innovator Жыл бұрын
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.
@NinjaRunningWild
@NinjaRunningWild Жыл бұрын
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 Жыл бұрын
I second that, that’d be awesome.
@the_beefy1986
@the_beefy1986 Жыл бұрын
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 Жыл бұрын
Yes, I'd like to know, too!
@bfth121
@bfth121 Жыл бұрын
@@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 Жыл бұрын
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.
@enochabban9454
@enochabban9454 Жыл бұрын
The blurred background is amazing. Makes me want to stay glued to the video.
@The_Gray_Zone_Man
@The_Gray_Zone_Man 4 ай бұрын
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.
@raymundhofmann7661
@raymundhofmann7661 Жыл бұрын
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 10 ай бұрын
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 10 ай бұрын
@@GamersUniverseOE Rvalue references wouldn't have much purpose without move semantics, or?
@davelaverie1799
@davelaverie1799 Жыл бұрын
Great to see the return of the Friendly Giant. I missed him.
@harshitjoshi3082
@harshitjoshi3082 Жыл бұрын
I definitely would have more videos about c++ intermediate topics, absolutely love the content! Thanks for making this
@DavesGarage
@DavesGarage Жыл бұрын
Very welcome, thanks for saying so!
@Hipdudester
@Hipdudester Ай бұрын
The Friendly Giant!!! You have just become my favorite C++ person. , Wow! great video learning a lot.
@vasiliosmagriplis
@vasiliosmagriplis Жыл бұрын
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 Жыл бұрын
Modern idiomatic C++ even avoids several pitfalls of old idiomatic C++
@realpainediaz7473
@realpainediaz7473 Жыл бұрын
@@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." 🙀😵😱
@velho6298
@velho6298 Жыл бұрын
I think one of the most important features from the C++11 was the move operation.
@irisaacsni
@irisaacsni Жыл бұрын
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 Жыл бұрын
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.
@irbaboon1979
@irbaboon1979 Жыл бұрын
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 :)
@Chris.Brisson
@Chris.Brisson Жыл бұрын
I've been a fan of the Standard Template Library since it's early days at HP.
@ghostlucian12
@ghostlucian12 Жыл бұрын
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 Жыл бұрын
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
@k34561
@k34561 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
shared ptrs created via make_shared do only 1 allocation
@NoNameAtAll2
@NoNameAtAll2 Жыл бұрын
how does embedded count work?
@pavelperina7629
@pavelperina7629 Жыл бұрын
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.
@henryjimenez4710
@henryjimenez4710 5 ай бұрын
Great video, thank you very much. You have the best explanations of code i've ever seen on the web.
@trnpsycho
@trnpsycho Жыл бұрын
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!
@joemccay9978
@joemccay9978 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
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 Жыл бұрын
@@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.
@Gastell0
@Gastell0 Жыл бұрын
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 Жыл бұрын
There used to be a language called C With Classes. The original C++ was effectively C With Classes 2.0
@toby9999
@toby9999 Жыл бұрын
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 Жыл бұрын
@@rightwingsafetysquad9872 C++ was originally called C with classes until it was renamed to C++
@zemlidrakona2915
@zemlidrakona2915 Жыл бұрын
"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 Жыл бұрын
@@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".
@75slaine
@75slaine Жыл бұрын
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. 👍
@Christian-op1ss
@Christian-op1ss Жыл бұрын
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!
@IanJohnstonblog
@IanJohnstonblog Жыл бұрын
Very good synopsis… I still get hit in my childhood feels with the friendly giant ending. The CBC overlay is also a nice touch. :)
@cablekiller
@cablekiller Жыл бұрын
love the coding content. keep em coming
@Gattancha
@Gattancha Жыл бұрын
Only just trying to get my head round C++ and your videos are great at trying to understand it all
@ze_rubenator
@ze_rubenator Жыл бұрын
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 7 ай бұрын
I picked it up in couple of hours, not that hard to be honest
@bertblankenstein3738
@bertblankenstein3738 Жыл бұрын
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 Жыл бұрын
"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 Жыл бұрын
"I'm a hobbyist and usually find myself debugging things where I am rotating or swapping elements in an array." That's a rotate.
@jrkorman
@jrkorman Жыл бұрын
Nice little review. Haven't really touched C/C++ in quite a number of years.
@GaryLuckenbaugh-xu8lr
@GaryLuckenbaugh-xu8lr Жыл бұрын
Dave, This is an exciting video. I see C++ in an entirely new light. Thank you so much!!
@Bonta768
@Bonta768 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
​@@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 Жыл бұрын
@@MyAmazingUsername Gosh programmers are soooooo arrogant sometimes. "Dave is never very knowledgeable" - bwahahahahaha.
@OrangeShellGaming
@OrangeShellGaming Жыл бұрын
@@davidblake8612 Rust coders are particularly infamous for their "holier than thou" attitude.
@SKULDROPR
@SKULDROPR Жыл бұрын
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 Жыл бұрын
Standard template library isn't exactly new. It was included in the C++ standard in -94.
@SKULDROPR
@SKULDROPR Жыл бұрын
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.
@vinniciusrosa8284
@vinniciusrosa8284 4 ай бұрын
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.
@gumbilicious1
@gumbilicious1 Жыл бұрын
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 Жыл бұрын
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...
@marksilverman
@marksilverman Жыл бұрын
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 Жыл бұрын
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.
@ze_rubenator
@ze_rubenator Жыл бұрын
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.
@ebred76
@ebred76 11 ай бұрын
Listening to you is like reading a condensed well written no fluff book, without the reading. Well done
@SomeRandomPiggo
@SomeRandomPiggo Жыл бұрын
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
@galbareket3995
@galbareket3995 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
​@@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 Жыл бұрын
@@MrHaggyy ah, thank you, let me correct myself
@norszabo
@norszabo Жыл бұрын
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 Жыл бұрын
So what's the better way to do it please?
@KohuGaly
@KohuGaly Жыл бұрын
@@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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@DavesGarage Moving the data to the vector?
@leosthrivwithautism
@leosthrivwithautism Жыл бұрын
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. 👍
@davidstewart4228
@davidstewart4228 Жыл бұрын
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.
@DavidRomigJr
@DavidRomigJr Жыл бұрын
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 Жыл бұрын
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.
@maddsua
@maddsua Жыл бұрын
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!
@akaalkripal5724
@akaalkripal5724 11 ай бұрын
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.
@TheExcellentVideoChannel
@TheExcellentVideoChannel Жыл бұрын
Nice work Dave. Much appreciate this kind of content.
@KoRNeRd
@KoRNeRd Жыл бұрын
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 Жыл бұрын
Right. Because Rust is the language for people who don’t know better…
@limitationsapply
@limitationsapply Жыл бұрын
The point is more that every programmer is a fallible human. Even if you "know better", you're not immune to mistakes.
@Upliner1
@Upliner1 Жыл бұрын
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.
@ultraenergy313
@ultraenergy313 Жыл бұрын
Thank you for making this simpler to understand
@k.alipardhan6957
@k.alipardhan6957 Ай бұрын
Thank you! As an experianced dev, this video was the exact level I wanted; You don't over explain and move fast
@muhdiversity7409
@muhdiversity7409 Жыл бұрын
Hi Dave! Oh, and first :)
@aneeshprasobhan
@aneeshprasobhan Жыл бұрын
nobody cares 4channer
@AK-vx4dy
@AK-vx4dy Жыл бұрын
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 Жыл бұрын
`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 Жыл бұрын
@@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 Жыл бұрын
@@AK-vx4dy `std::unique_ptr` is not a pointer to a pointer. And there is no runtime check.
@AK-vx4dy
@AK-vx4dy Жыл бұрын
@@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 Жыл бұрын
@@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.
@johnburgess2084
@johnburgess2084 Жыл бұрын
I loved this explanation and tutorial; please continue with this series!
@LA-MJ
@LA-MJ Жыл бұрын
You skipped over the hand value method but here we are actually doing something interesting: borrowing cards for the hand
@agdevoq
@agdevoq Жыл бұрын
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...
@NoNameAtAll2
@NoNameAtAll2 Жыл бұрын
...new? aren't smart pointers a decade old?
@stepannovotny4291
@stepannovotny4291 Жыл бұрын
I enjoy your recent videos such as this one, which are of interest to people learning embedded programming.
@DavesGarage
@DavesGarage Жыл бұрын
Thanks, I'll keep trying to do more and see if I can build an audience!
@henrikarboejensen812
@henrikarboejensen812 Ай бұрын
I wish I could think that unwavering and plow through programming logic in calm order that fast. Sharp as a knife. As if I was talking casually on the way to the bus. Now I understand what Bill meant with assigning to projects the right 10 or fewer people.
@wertigon
@wertigon Жыл бұрын
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.
@cookoo4lyf
@cookoo4lyf Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 9 ай бұрын
​@@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 7 ай бұрын
​@@scififan698C# is definitely not better lmao you ate wrong mushrooms
@adamploof3528
@adamploof3528 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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.
@vuduyhung-Hungsiro
@vuduyhung-Hungsiro Жыл бұрын
Thanks for helpful video. Please do more of this series.
@stysner4580
@stysner4580 Жыл бұрын
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 7 ай бұрын
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 7 ай бұрын
@@AshishSinghh well... Microsoft and Linux disagree with you... don't underestimate the cost of unsafe code in bot dev time and potential bugs.
@johndowson1852
@johndowson1852 Жыл бұрын
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 Жыл бұрын
If you shoot yourself in the foot, don't blame the holster, blame the operator, I figure!
@cookie04
@cookie04 Жыл бұрын
@@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.
@johnmckown1267
@johnmckown1267 Жыл бұрын
Will mention that I had problems with this due to an error in random_device in MinGW always generating the same sequence of numbers. Downloaded and installed Clang and it worked great. The MinGW bug was fortunate because it made me really study the code and refresh my old knowledge of C++.
@viberaeip7143
@viberaeip7143 2 ай бұрын
Congrats , this blows the competition away …, most of the tutorials don’t give you those nuances, perspectives molded by decades of experience
@iincognito96
@iincognito96 Жыл бұрын
idk why people hype up rust so much they probably dont know any c++
@TheFreeSpiritKID
@TheFreeSpiritKID Жыл бұрын
Well it's typesafe, simple and blazingly fast
@NinjaRunningWild
@NinjaRunningWild Жыл бұрын
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 Жыл бұрын
Just "const" everything in C++. Done.
@us07251
@us07251 Жыл бұрын
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 Жыл бұрын
@@NinjaRunningWild Nope. Rust only exists because of a lot of hard work trying a new approach.
@AbelShields
@AbelShields Жыл бұрын
"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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
@@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 6 ай бұрын
@@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 3 ай бұрын
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.
@marrtins
@marrtins Жыл бұрын
Please more programming videos including stories about programming from you carrier - serious or funny ones! Thanks for the content! It's great!
@sorbpen
@sorbpen Жыл бұрын
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 Жыл бұрын
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.
@ManInTheAttic57
@ManInTheAttic57 Жыл бұрын
Great example and explanation. Thank you.
Did you find it?! 🤔✨✍️ #funnyart
00:11
Artistomg
Рет қаралды 124 МЛН
FOOTBALL WITH PLAY BUTTONS ▶️ #roadto100m
00:29
Celine Dept
Рет қаралды 75 МЛН
Ну Лилит))) прода в онк: завидные котики
00:51
The Worlds Most Powerfull Batteries !
00:48
Woody & Kleiny
Рет қаралды 21 МЛН
My 2 Year Journey of Learning C, in 9 minutes
8:42
VoxelRifts
Рет қаралды 541 М.
E00: Software Drag Racing:  C++ vs C# vs Python - Which Will Win?
23:30
WHY did this C++ code FAIL?
38:10
The Cherno
Рет қаралды 81 М.
31 nooby C++ habits you need to ditch
16:18
mCoding
Рет қаралды 717 М.
C++ Super Optimization: 1000X Faster
15:33
Dave's Garage
Рет қаралды 279 М.
Why i think C++ is better than rust
32:48
ThePrimeTime
Рет қаралды 267 М.
C vs ASM: Making the World's SMALLEST Windows App
20:15
Dave's Garage
Рет қаралды 140 М.
Your Home Network is Exposed: Top 10 Ways to Protect it NOW!
18:19
Dave's Garage
Рет қаралды 174 М.
Your understanding of evolution is incomplete. Here's why
14:21
C++ vs Rust: which is faster?
21:15
fasterthanlime
Рет қаралды 371 М.
What’s your charging level??
0:14
Татьяна Дука
Рет қаралды 7 МЛН
5 НЕЛЕГАЛЬНЫХ гаджетов, за которые вас посадят
0:59
Кибер Андерсон
Рет қаралды 941 М.
Обзор игрового компьютера Макса 2в1
23:34
Apple, как вас уделал Тюменский бренд CaseGuru? Конец удивил #caseguru #кейсгуру #наушники
0:54
CaseGuru / Наушники / Пылесосы / Смарт-часы /
Рет қаралды 4,5 МЛН
Эффект Карбонаро и бумажный телефон
1:01
История одного вокалиста
Рет қаралды 2,6 МЛН