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!

КОМЕНТАРІ • 42

  • @yb9737
    @yb9737 2 роки тому +33

    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

    • @MikeShah
      @MikeShah  2 роки тому +4

      Thank you for the kind words :) More to come, spread the word!

    • @k0185123
      @k0185123 7 місяців тому

      Totally agreed!!!

  • @peerajak
    @peerajak 8 місяців тому +1

    Why don't we just use stack variable, then? One name for one memory (on stack). Destroy together with stack memory?

    • @MikeShah
      @MikeShah  8 місяців тому +1

      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.

  • @QWin-ir6yq
    @QWin-ir6yq 4 місяці тому +1

    Which of the smart pointers best resemble a raw pointer?

    • @MikeShah
      @MikeShah  4 місяці тому

      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).

  • @joebosah2727
    @joebosah2727 Рік тому +1

    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?

    • @MikeShah
      @MikeShah  Рік тому

      Yup, you could use auto there for sure, auto will deduce the type automatically.

    • @joebosah2727
      @joebosah2727 Рік тому

      @@MikeShah thank you. It’s 3:55am here

  • @wpfbeginner
    @wpfbeginner 7 місяців тому

    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?

    • @MikeShah
      @MikeShah  7 місяців тому

      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.

  • @menachemlevi
    @menachemlevi 7 місяців тому +3

    best teacher ever ,subscribe guys lets make him big

    • @MikeShah
      @MikeShah  7 місяців тому

      Cheers -- very kind of you! :)

  • @Kirfx
    @Kirfx 9 місяців тому +1

    Wow! Not even a warning for wrong delete! 🤯 And it runs everywhere on everything 😅

    • @MikeShah
      @MikeShah  9 місяців тому

      Timestamp?

    • @Kirfx
      @Kirfx 9 місяців тому

      @@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.

    • @MikeShah
      @MikeShah  9 місяців тому

      I would think most static analysis would catch this type of bug -- but you are correct that you should be a delete[] :) @@Kirfx

  • @wika96
    @wika96 Рік тому +1

    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.

    • @MikeShah
      @MikeShah  Рік тому +1

      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.

    • @wika96
      @wika96 Рік тому

      @@MikeShah Thank you

  • @dhanushs1802
    @dhanushs1802 2 роки тому +2

    Very well explained as always. Thank you.

  • @edoardogribaldo2870
    @edoardogribaldo2870 Рік тому +3

    Astonishing explanation !

  • @syed6044
    @syed6044 2 роки тому +2

    Thank you very much Mike...

    • @MikeShah
      @MikeShah  2 роки тому

      You're most welcome!

  • @7guitarlover
    @7guitarlover Рік тому

    @ 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 ?

  • @k0185123
    @k0185123 7 місяців тому +1

    Goooooooooood!!!!!!!!!!!!!!!!

  • @yea-yea
    @yea-yea Рік тому

    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!

    • @MikeShah
      @MikeShah  Рік тому

      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.

  • @mav474
    @mav474 Рік тому +2

    Thanks Mike

  • @klutch4198
    @klutch4198 2 роки тому +1

    I see a Cambridge shirt! Are you from Mass?!

    • @MikeShah
      @MikeShah  2 роки тому +2

      Not originally, but yes spend time in Mass nowadays! New England is wonderful!

    • @klutch4198
      @klutch4198 2 роки тому +1

      @@MikeShah Glad you enjoy it!!
      I'm Western Mass native myself thats why I had to ask haha

    • @MikeShah
      @MikeShah  2 роки тому +1

      @@klutch4198 Awesome!

    • @klutch4198
      @klutch4198 2 роки тому +1

      @@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)

    • @MikeShah
      @MikeShah  2 роки тому +1

      @@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.