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 Жыл бұрын
Yep, me too
@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.
@jacobesplin20 Жыл бұрын
I am also interested in more videos like this. It would be really cool to know how these methods change performance?
@forbiddenera Жыл бұрын
Agree! My cpp is weak these days
@CristiNeagu Жыл бұрын
@@samueltulach I don't know enough about C++ and its usual application, but it seems to me that direct memory management is far from the common use case. I think there is a pretty good reason why Dave said that using the old C memory allocation and release methods is bad C++.
@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 Жыл бұрын
Hear hear...
@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 Жыл бұрын
school level teaches what algorithm is, not how to program with memory control...
@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 Жыл бұрын
You can thank your school teacher for your ability yo understand this more advanced lesson.
@snobaste Жыл бұрын
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!
@poushankumarbiswas8693 Жыл бұрын
Sir, you should now really start considering teaching here on KZbin. 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 Жыл бұрын
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.
@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!
@enochabban9454 Жыл бұрын
The blurred background is amazing. Makes me want to stay glued to the video.
@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 Жыл бұрын
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 Жыл бұрын
Imagine how I, a VB6 programmer, feels ...
@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 Жыл бұрын
@@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 Жыл бұрын
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.
@69k_gold3 ай бұрын
I love your holistic approach, instead of teaching just the concept, you ensure the viewer can digest the information(like how you dealt with std::vector's poor naming)
@rickpoeling6831 Жыл бұрын
Excellent working example. Your coding style is extremely efficient and easily understood.
@Sonavyon Жыл бұрын
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!
@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!
@josephbaker9932 Жыл бұрын
Thanks for the reminder of the Friendly Giant. I am 60 and grew up in BC before moving to the States. I had completely forgot that childhood memory.
@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 Жыл бұрын
I am working on a performance and memory sensitive application and I will try this to see if it saves me some ram, thanks 🙏
@june_m12 Жыл бұрын
wouldn't this need to reallocate? or does it just trim?
@JATmatic Жыл бұрын
@@june_m12 It might do reallocation, it is implementation defined. Depends likely how much excess capacity the vector has.
@denkalenichenko4124 Жыл бұрын
@@JATmaticIm not sure, but C++ doesn't have own reallocate. Only C realloc
@zeez7777 Жыл бұрын
@@denkalenichenko4124 Yes so that is still c++, its a superset of C
@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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
@@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.
@akaalkripal5724 Жыл бұрын
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.
@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 Жыл бұрын
Thanks, I appreciate you saying so!
@ebred76 Жыл бұрын
Listening to you is like reading a condensed well written no fluff book, without the reading. Well done
@TractorWrangler01 Жыл бұрын
You are an excellent teacher Dave.
@viberaeip71438 ай бұрын
Congrats , this blows the competition away …, most of the tutorials don’t give you those nuances, perspectives molded by decades of experience
@delsorou Жыл бұрын
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.
@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 Жыл бұрын
> 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 Жыл бұрын
That sounds perfectly useless. Why handicap yourself like that?
@NoSpeechForTheDumb3 ай бұрын
std::string is ugly, but like everything in std it's efficient as hell. If you do anything like sophisticated processing on big texts, Java is completely unappropriate. That's why literally all modern text editors are written in C++ (or hopefully Rust in the future).
@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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
@@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.
@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.
@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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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"`.
@k.alipardhan69577 ай бұрын
Thank you! As an experianced dev, this video was the exact level I wanted; You don't over explain and move fast
@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.
@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.
@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 Жыл бұрын
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 Жыл бұрын
@@GamersUniverseOE Rvalue references wouldn't have much purpose without move semantics, or?
@Chris.Brisson Жыл бұрын
I've been a fan of the Standard Template Library since it's early days at HP.
@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 Жыл бұрын
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 Жыл бұрын
shared ptrs created via make_shared do only 1 allocation
@NoNameAtAll2 Жыл бұрын
how does embedded count work?
@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.
@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.
@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 Жыл бұрын
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...
@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".
@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 Жыл бұрын
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 Жыл бұрын
@@davidblake8612 C# is, or at least was Java. MS got to pay a pretty penny for that in the start of the milennium.
@davidblake8612 Жыл бұрын
@@karsh001 What?
@karsh001 Жыл бұрын
@@davidblake8612 google should take you there: settled of of court 2001 Sun Java Microsoft C# settlement.
@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.
@scififan698Ай бұрын
glad to see you use pre-increment in your for loops. Most people don't know why this is superior.
@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 Жыл бұрын
Modern idiomatic C++ even avoids several pitfalls of old idiomatic C++
@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." 🙀😵😱
@2teaspoon Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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.
@velho6298 Жыл бұрын
I think one of the most important features from the C++11 was the move operation.
@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 Жыл бұрын
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.
@dazecm5 ай бұрын
It's always great when a language gives you nice features to help prevent you from blowing off your own foot.
@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 Жыл бұрын
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
@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 Жыл бұрын
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.
@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 Жыл бұрын
I second that, that’d be awesome.
@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 Жыл бұрын
Yes, I'd like to know, too!
@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 Жыл бұрын
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.
@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. 👍
@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]
@johnglielmi6428 Жыл бұрын
Most of us C++ users are of the OOP programming genre. Classes are a major part of OPP. thank you for teaching myself and others a more efficient way of OPP programming.
@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 Жыл бұрын
I picked it up in couple of hours, not that hard to be honest
@harshitjoshi3082 Жыл бұрын
I definitely would have more videos about c++ intermediate topics, absolutely love the content! Thanks for making this
@DavesGarage Жыл бұрын
Very welcome, thanks for saying so!
@davelaverie1799 Жыл бұрын
Great to see the return of the Friendly Giant. I missed him.
@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 Жыл бұрын
Ah Fortran. I used to code in that too. It's actually not a bad language at all.
@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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
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 Жыл бұрын
@@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.
@digitald2007 Жыл бұрын
Another great video. And, as a Canadian, I really liked the Friendly Giant ending. :)
@renod424 ай бұрын
Ditto. I certainly watched TFG as a kid. I haven’t coded in c++ for about 30 years. So found this informative.
@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. :)
@anoniemoss35663 ай бұрын
I'm so glad you did this a card game example. This was a model I use myself learn how to manage collections and references/ pointers in any language I'm learning. Trying to do this in C was fun, but a pain in the ass and I had new respect for managed languages like C#.
@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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
@@MyAmazingUsername Gosh programmers are soooooo arrogant sometimes. "Dave is never very knowledgeable" - bwahahahahaha.
@OrangeShellGaming Жыл бұрын
@@davidblake8612 Rust coders are particularly infamous for their "holier than thou" attitude.
@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!
@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 Жыл бұрын
There used to be a language called C With Classes. The original C++ was effectively C With Classes 2.0
@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 Жыл бұрын
@@rightwingsafetysquad9872 C++ was originally called C with classes until it was renamed to C++
@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 Жыл бұрын
@@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".
@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.
@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 Жыл бұрын
"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 Жыл бұрын
"I'm a hobbyist and usually find myself debugging things where I am rotating or swapping elements in an array." That's a rotate.
@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 :)
@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 KZbin: `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.
@Rexhunterj7 ай бұрын
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.
@JohnWDisco4 ай бұрын
20yrs ago when I was a kids learning how to code, I was afraid of C++ was to hard. Granted I was 12… touched it until helping with a friend created sensors for his windmill, with WiFi, Bluetooth and updates when away, plus remote updates to the ESP32. Arduino is perfect for people to dip their tones in. Many years later, C is my number one first choice.
@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 Жыл бұрын
Standard template library isn't exactly new. It was included in the C++ standard in -94.
@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.
@SwapChain Жыл бұрын
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.
@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 Жыл бұрын
So what's the better way to do it please?
@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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@DavesGarage Moving the data to the vector?
@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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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.
@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.
@jrkorman Жыл бұрын
Nice little review. Haven't really touched C/C++ in quite a number of years.
@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 Жыл бұрын
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.
@linuxgaminginfullhd60fps105 ай бұрын
vector is just an array. This is so true! I remember I was very confused by this name. So I had to understand that vector is not a vector as in math. And then I have to understand that it is indeed an array, that it's elements are contiguous, random access and, all of the same size and getting the pointer to the first element is actually the pointer that can be used as an array. So it is indeed an array. There is also an "array" in C++, which is an array with a fixed number of elements determined at compile time, unlike for example variable length arrays.
@cablekiller Жыл бұрын
love the coding content. keep em coming
@Karenware Жыл бұрын
Thanks, Dave. I'm the c programmer from the 80's turned c++ programmer in the 90's like whom you were talking to.
@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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
@@scififan698C# is definitely not better lmao you ate wrong mushrooms
@TheTrienco Жыл бұрын
Great demonstration of how to use the classes. The only downside of it being a simple example is that you would typically never bother with dynamically allocated memory and unique_ptr to manage a class that only stores 2 ints and can fit into a CPU register. I would argue that copying a Card is likely even faster than moving from one unique_ptr to another. And of the course more of a personal preference is "let dumb data be dumb data". Making Card a struct with const members would make them un-assignable. Usually a problematic limitation, but in this case a perfect (though artificial) reason to use vector in the first place.
@DavesGarage Жыл бұрын
But it isn't... std::move() on a unique_ptr is four bytes of memory copied, but copying the entire struct context takes more time. Granted, you're right in that the Card class is pretty trivial... but it's an example, and most structs/classes have more than 2 member vars.
@TheTrienco Жыл бұрын
@@DavesGarage That's what I meant with "downside of it being a simple example". Moving from a unique_ptr has to copy 4 bytes, but also clear the original pointer (assuming the implementation isn't wasting space for a separate flag). A good default assumption is that "move = swap". With the struct also being 4 bytes (enum usually defaults to int if not explicitly specified otherwise). Not sure what you refer to with "struct context". Type info or memory management data maybe? If so, as long as the data stays inside the vector, the overhead per card should be zero. If we talk about performance, unique_ptr is actually pretty horrible in some use cases. A vector stores all cards consecutively in memory and makes the cache happy. vector will dynamically allocate each Card independently and they can be peppered all over your memory. There is also the extra indirection when accessing the data. But I don't see that as a problem, seeing how the point of the example is to demonstrate vector and unique_ptr, not squeezing out every last bit of performance. On the other hand, if there is ever a follow up about the benefits of keeping your data in a cache friendly way, comparing things like sort/shuffle/find on vector vs vector could be interesting. In which scenario does it matter? How much does it matter? How bad do all the dynamic allocations hurt when creating the deck (or rather, how many Cards would it take before the difference becomes noticeable)? Is there any optimization happening that can prevent it (like the small data/short string optimizations with vector/string classes)?
@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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
@@MrHaggyy ah, thank you, let me correct myself
@leafylotus Жыл бұрын
Hey Dave, these C++/C insights are friggin amazing. Thank you
@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 Жыл бұрын
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.
@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 Жыл бұрын
Thanks, I appreciate that!
@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!
@vinniciusrosa82849 ай бұрын
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.
@theonetribble5867 Жыл бұрын
One problem with st::vector is that if you take a pointer to an element and you push another element to that vector you can still end up with dangling pointers. That's why Rust has the borrow checker. Using std::unique_ptr or std::shared_ptr in vectors on the other hand can result in quite large performance hits due to the allocations and access indirections resulting from their use. Rust has similar types such as Box and Rc/Arc but you don't have to use them in a Vector usually.
@DavesGarage Жыл бұрын
I don't think that's accurate. Post a code snippet where you think this occurs.
@limitationsapply Жыл бұрын
@@DavesGarage Use-after-free, push_back invalidates ptr if it chooses to resize the vector: std::vector v{1, 2, 3}; int* ptr = &v[0]; v.push_back(4); v.push_back(*ptr); This is a compile error in Rust, as ptr would be an immutable borrow from v, preventing push() from taking a mutable borrow.
@Somun-a Жыл бұрын
"Using std::unique_ptr or std::shared_ptr in vectors on the other hand can result in quite large performance hits due to the allocations and access indirections resulting from their use" You might not be realizing that unique_ptr is a compile time construct only. There is simply no run-time performance penalty. Trying to get the address of an element in the vector is allowed but it does not make it a good idea (not sure what to motivation would be). So, your code snippet is making a semantic error which is also referred as iterator invalidation. Inserting elements to a vector invalidates the existing iterators. C++ has all the tools, including the ones you can shoot yourself in the foot, with, if you want to.
@theonetribble5867 Жыл бұрын
@@Somun-a Sorry for the somewhat long and convoluted explanation. About the std::unique_ptr: When testing the code snippet on my machine, the variant using unique pointers was about 5 to 10 times slower (1118 vs 153 ms). If you'd like you can test it your self. Shared pointers in particular would have to allocate memory since they are reference counting pointers and lie on the heap. About the use after free issue: I agree with your statement, that the snippet makes a semantic error, however the "problem" is that C++ allows this error. Rust does not for this case. This does not mean that Rust does not give you "all the tools". You can do anything in Rust that you could do in C++, it just needs to be declared unsafe if you want to be able to shoot your self in the foot. In fact most (hard to define "most") of rusts stdlib has unsafe code, however this is code that is guaranteed to be save and anything based on it is also (memory) safe (If you don't use the unsafe keyword). As an example, Rusts equivalent to std::vector is Vec and initialized via the vec! macro. The following snippet does not compile in Rust. fn main(){ let mut v = vec![1]; let r = &v[0]; v.push(2); // Borrow checker would complain that you are trying to modify v while keeping a reference to the (an element of) the Vec println!("{}", *r); } The compile time Error occurs because you are taking (borrowing) a immutable and mutable reference to Vec at the same time which is not allowed in safe rust. However you could take a pointer (even in safe code) you just cannot de-reference it outside of an unsafe block. fn main(){ let mut v = vec![1]; let ptr = &v[0] as *const _; v.push(2); unsafe{ println!("{}", *ptr); } } This is unsafe Rust code and suffers from the same problem as the C++ example but You have to declare it as such. The job of anyone writing unsafe code is then to validate (logically provable or via testing for Foreign Function Interfaces (Calling C/C++ code)). It is also highly encouraged to put a SAFETY comment before any unsafe code block that declares your reasoning for why this code should be safe. I hope this could help you understand a little how rust enforces memory safety without preventing you from programming efficient code.
@limitationsapply Жыл бұрын
@@Somun-a "You might not be realizing that unique_ptr is a compile time construct only. There is simply no run-time performance penalty." It's a pointer, it's fundamentally a run-time performance penalty compared with just using the vector for storage. But it is safer, because you don't invalidate the pointer if the vector is resized. "C++ has all the tools, including the ones you can shoot yourself in the foot, with, if you want to." If C++ only shot you in the foot when you wanted it to we wouldn't be having this conversation.
@NoNameAtAll2 Жыл бұрын
...new? aren't smart pointers a decade old?
@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!
@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 Жыл бұрын
Right. Because Rust is the language for people who don’t know better…
@limitationsapply Жыл бұрын
The point is more that every programmer is a fallible human. Even if you "know better", you're not immune to mistakes.
@johngray2875 Жыл бұрын
I did a lot of C++ work in the very early days on C++. Very nice writing that without a single new call.
@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...
@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++.
@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.
@Gattancha Жыл бұрын
Only just trying to get my head round C++ and your videos are great at trying to understand it all
@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 Жыл бұрын
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 Жыл бұрын
@@AshishSinghh well... Microsoft and Linux disagree with you... don't underestimate the cost of unsafe code in bot dev time and potential bugs.
@eulondon Жыл бұрын
I am at college in Brazil. Yet never learned this concept of ownership of an obejct. Really cool, and also leaves you free of unnecessary checks and code. Going to keep an eye for this in other languages. Than you.
@00SEVEN28 Жыл бұрын
This was one reason I learned Rust, to better understand ownership and lifetime.
@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.
@VoidloniXaarii Жыл бұрын
Thnx zo much 4 fighting against c++ rusting! Saying this as an ex east European who feels that as I was winning county first place physics competitions u were actually not just able to solve but maybe even writing the smirnov books that were crushing my otherwise ambitious with soul. Thanks uz!
@DavesGarage Жыл бұрын
Think of Rust as a much safer table saw, whereas C++ is a dangerous compound mitre saw. Both can cut wood safely, but one has the power to do much more complex work (and sever your arm).
@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 Жыл бұрын
`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 Жыл бұрын
@@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 Жыл бұрын
@@AK-vx4dy `std::unique_ptr` is not a pointer to a pointer. And there is no runtime check.
@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 Жыл бұрын
@@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.
@dylon4906 Жыл бұрын
awesome coincidence that this video just came out considering that i have a final for my college CS class in a few days thats over c++ arrays, vectors, and pointers
@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 Жыл бұрын
If you shoot yourself in the foot, don't blame the holster, blame the operator, I figure!
@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.
@davidblake8612 Жыл бұрын
Great video thanks Dave. I used to code in C++ 20 years ago. I still have the books on my shelf 1m away from me. I can't bring myself to get rid of them. I still have a large soft spot for C++. I mainly use Python and Go now. But I'm nostalgic for C++.
@khatdubell Жыл бұрын
Since C++ 20 is a thing, that could sound like "Years ago, i used to code in C++ 20" vs "20 years ago i used to code in C++"
@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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
@@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 Жыл бұрын
@@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.”
@PeterMoore-q5k9 ай бұрын
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.
@kilaposhi Жыл бұрын
Great video, clear explanations. I need more modern C++ examples like that!
@yahm0n Жыл бұрын
The exciting part about newer languages is really that they form fresh ecosystems of libraries that are all on the same page with regards to newer language features.