std::unique_ptr - A scoped smart pointer | Modern Cpp Series Ep. 33
Вставка
- Опубліковано 1 жов 2024
- ►Full C++ Series Playlist: • The C++ Programming La...
►Find full courses on: courses.mshah.io/
►Join as Member to Support the channel: / @mikeshah
►Lesson Description: In this lesson I show you how to use a std::unique_ptr. I will show you why we might want to use this smart pointer versus a raw pointer, and how to create this pointer. While we haven't covered classes yet in this series, it's important to realize that this smart pointer is essentially a 'wrapper' around a raw pointer that calls the destructor to free memory when the pointer leaves scope.
Note: Something not covered in this lesson is the idea of a 'custom deleter' which can be useful.
►UA-cam Channel: / mikeshah
►Please like and subscribe to help the channel!
I can't believe I'm getting world class content for free from one of the best c++ influencer/programmer out there. This channel is underrated by a huge margin. Thanks Mike
Thank you for the kind words :) More to come, spread the word!
Totally agreed!!!
Why don't we just use stack variable, then? One name for one memory (on stack). Destroy together with stack memory?
Might need to allocate on run-time either something that is variable size, or otherwise if we have a large allocation, we need a pointer. That said, we could just make one very large allocation at run-time and then manage the memory ourselves with a local-arena, which is in fact what some applications do.
Which of the smart pointers best resemble a raw pointer?
None of them really -- each smart pointer is putting some restriction to help you write safer code. A quick summary:
shared_ptr is the most flexible, and still saves you from double-frees -- so perhaps this is the closest in some sense. weak_ptr may or may not be valid memory (but you can check, and still allows you to share memory), and unique_ptr is exactly a pointer, except you can only have ownership of one piece of memory (limiting sharing).
Keep coming back to this just to sink in.
Can we replace( line 21, 14.48mins time elapse) “std::unique_ptr mike_array = std::make_unique(10);” with
“auto mike_array{make_unique(10)};”
It seems to be working on MVS 2022 with either ISO 14,17, 20 as default.
What’s the difference?
Yup, you could use auto there for sure, auto will deduce the type automatically.
@@MikeShah thank you. It’s 3:55am here
Good explanation. On line 20, after you move mike to joe, if you access mike what happens. Is it caught at the compilation time or runtime?
Going to be caught at runtime unless your compiler or tooling provides a warning on later access. It depends on the datatype, but most likely the 'move' operation will make 'mike' a nullptr and then give you a segfault.
best teacher ever ,subscribe guys lets make him big
Cheers -- very kind of you! :)
Wow! Not even a warning for wrong delete! 🤯 And it runs everywhere on everything 😅
Timestamp?
@@MikeShah 4:40. I mean program compiles with wrong delete call, doesn't throw a warning, doesn't crash just silently leak memory. I bet this behaviour is sitting there for many years and for some reason wasn't fixed. Instead it's recomended to do Coding Standards and Reviews, Smart Pointers, Custom Allocators, Static Analysis Tools, Modern C++ Features. These recommendations are all great, but what about fixing obviously dangerous behaviour or at least to warn the programmer with message from compiler? I'm just trying to estimate how dangerous C++ programming actually is.
I would think most static analysis would catch this type of bug -- but you are correct that you should be a delete[] :) @@Kirfx
Great video Mike. Could you clarify this for me? Can we pass a unique pointer through threads? What would be the behavior? Thank you very much.
If those threads are only reading the value without any synchronization, then you can assume thread-safe. If some threads are reading/writing, then unique_ptr is not immune to thread-safety issues. For example, a thread could call unique_ptr::get and then essentially break the invariant around the 'uniqueness' of the unique_ptr.
@@MikeShah Thank you
Very well explained as always. Thank you.
Cheers!
Astonishing explanation !
Cheers!
Thank you very much Mike...
You're most welcome!
@ Dr mike is there a difference between move and release function in unique_ptr.
Is unique_ptr p1 = make_unique(10);
unique_ptr q1 = std::move(p1) ;
vs
unique_ptr p1 = make_unique(10);
unique_ptr q1 = p1.release() ;
fundamentally the same ?
Goooooooooood!!!!!!!!!!!!!!!!
Hi Mike! Great explanations as always, thank you very much for the excellent content!
I would have a question tho: I understand what unique_ptr is or that it can't be copied but moved, its resource (pointee) can be pointed by only that particular uniue_ptr etc. However, I still don't really get "when" do we need it? Can you give a real life example where we have single ownership of a resource so that we need a unique pointer there?
P.S. I am actually planning to ask the same question for shared_ptr as well on shared_ptr video. So, if you'd like to answer both here, I would appreciate. If not, I would still appreciate your unique_ptr real life example here :)
Thanks a lot again!
Anywhere you would use a raw pointer, you can use a std::unique_ptr. So any time you heap allocate with new, consider substituting with a unique_ptr if exactly 1 thing is going to have a reference to that piece of memory. So for example, if you are loading a bunch of text data from a file into a buffer, you might heap allocate a large collection of bytes that are read into that buffer. If multiple objects need to look at that buffer, then use a shared_ptr, otherwise a unique_ptr.
Thanks Mike
Cheers!
I see a Cambridge shirt! Are you from Mass?!
Not originally, but yes spend time in Mass nowadays! New England is wonderful!
@@MikeShah Glad you enjoy it!!
I'm Western Mass native myself thats why I had to ask haha
@@klutch4198 Awesome!
@@MikeShah Just curious - do you have any ideas for some program ideas I should build for practice? I've built hundreds of apps of all kinds (I am a developer) but when it comes to CPP all I have so far is my magic eight ball haha. It's just so powerful and fast that program ideas for langs like C, Rust, etc. can be a little tricky because of said power and speed. Also, I'm currently writing cpp for the course on a raspberry PI instead of my mac mini just for it's simplicity with linux (so I dont mess with my current dev environment on mac)
@@klutch4198 very cool! As for projects, there's a nice summary here of some ideas: austinhenley.com/blog/challengingprojects.html I think any of these are great for cpp practice. If you do anything gaming related, my SDL2 or SFML series can help get you setup.