SMART POINTERS in C++ (std::unique_ptr, std::shared_ptr, std::weak_ptr)

Patreon ► / thecherno
Twitter ► / thecherno
Instagram ► / thecherno
Discord ► thecherno.com/discord
Series Playlist ► • C++
Thank you to the following Patreon supporters:
- Samuel Egger
Gear I use:
-----------------
BEST laptop for programming! ► geni.us/pakTES
My FAVOURITE keyboard for programming! ► geni.us/zNhB
FAVOURITE monitors for programming! ► geni.us/Ig6KBq
MAIN Camera ► geni.us/t6xyDRO
MAIN Lens ► geni.us/xGoDWT
Second Camera ► geni.us/CYUQ
Microphone ► geni.us/wqO6g7K

Пікірлер: 549

  • @cpdorli
    @cpdorli6 жыл бұрын

    This is one of the best series about C++. It's clear, it's fast and it has a charming and confident tutor.

  • @catorials444

    @catorials444

    3 жыл бұрын

    Agrreed

  • @amp2amp800

    @amp2amp800

    3 жыл бұрын

    That's exactly what I like too!

  • @anmararw

    @anmararw

    Жыл бұрын

    Definitely

  • @zanagi

    @zanagi

    5 ай бұрын

    6 years later, also yes

  • @peligros13
    @peligros132 жыл бұрын

    A bit late but after listening to several experts, it seems that the authors of the standard and the guidelines are VERY clear about when to use raw or smart pointers. I'll try to summarize them. 1. NEVER use new or delete. It has to be very clear wether a pointer owns the object or doesn't. If it owns the object (for example, it is creating the object), use a smart pointer and make_unique or make_shared. 2. By default, use unique_ptr because it has almost no overhead. If you know it will need to have several owners, use shared_ptr. 3. When the pointer will not own the object, use raw pointers. For example, when passing an object to a function, the pointer that receives it will not own the object (it will still be alive once the function returns), so don't pass the smart pointer, pass a raw pointer. To pass a unique_ptr as a raw pointer to a function, the best way is to dereference it and pass it by reference. So the function is just for example "void foo(const Class& myObject)", and you call it with "foo(*myPointer)". Another way would be to pass the adress itself, with the method "unique_ptr.get()". 4. Again, never use delete on a raw pointer and assume it does not own the object. 5. When you create an object inside a function and want to return it, do it as a unique_ptr. The receiver will be able to do whatever they want with it. Keep in mind that now, passing a local object from a function by copy will not actually copy it, but move it as an r-value. So it will move into the new unique_ptr, without a compiler error. Again, the receiver can do whatever they want, so they can move it into a shared_ptr or even a raw pointer. 6. When you want to transfer ownership of a unique_ptr, you can do it as a r-value using std::move(). This is basically what I just explained that C++ does when returning from a function. You can do it to transfer the ownership to a function. These are the basic guidelines with which you will probably never have memory leaks or loose pointers, they helped me a lot.

  • @jrsbenevides

    @jrsbenevides

    Жыл бұрын

    Thanks for this nice summary!!

  • @user-vs6kl8ph5v

    @user-vs6kl8ph5v

    Жыл бұрын

    wow, I should save this comment

  • @MrMShady

    @MrMShady

    Жыл бұрын

    Never too late my friend. Im learning only today - thanks for sharing!

  • @lcppproductions7910

    @lcppproductions7910

    9 ай бұрын

    Thx. This helps a lot.

  • @ObsessiveClarity

    @ObsessiveClarity

    6 ай бұрын

    LOL better organized / more concise summary in a youtube comment than in any article ive seen. Thank u

  • @everettmthunzi
    @everettmthunzi3 жыл бұрын

    These are no mere tutorials ... no, my good friends, these are timeless works of art! Your work is much appreciated!

  • @erawanthewise8227

    @erawanthewise8227

    2 жыл бұрын

    >>

  • @leixun
    @leixun4 жыл бұрын

    *My takeaways:* 1. Smart pointers are used to automatically assign and delete heap memory 0:25 2. Unique pointer 1:12 3. Shared pointer 5:00 4. Weak pointer 8:20 5. When should we use them 9:30

  • @bulentgercek

    @bulentgercek

    3 жыл бұрын

    @Lei Xun Thanks mate

  • @rishitsingh6621

    @rishitsingh6621

    3 жыл бұрын

    Thanks a lot, again

  • @leixun

    @leixun

    3 жыл бұрын

    @@rishitsingh6621 You are welcome

  • @minoset6037

    @minoset6037

    Жыл бұрын

    sex

  • @LucidStew
    @LucidStew6 жыл бұрын

    Thanks for the video. Didn't get smart pointers in any of my C++ classes since colleges still teach C++98 :\

  • @groberti

    @groberti

    5 жыл бұрын

    @@DelicueMusic they usually still use NULL instead of nullptr, so yeah...

  • @zoedesvl4131

    @zoedesvl4131

    5 жыл бұрын

    @@DelicueMusic Some schools still use VC++6.0 with ancient C++ standard. In my opinion, they just want to be 'stable'. But I don't by their opinion at all. Computer is still developing in a high speed, teaching outdated things is a waste of time. Laws of calculus remain the same for hundreds of years but computer doesn't.

  • @zoedesvl4131

    @zoedesvl4131

    5 жыл бұрын

    @@nijucow Some schools are afraid of the risk of major changes. Hence they never leave the outdated things. Seems like students are taught to deal with legacy codes only. In my opinion it goes like... Keep teaching a child ancient Greek language. Cool but can they communicate with others at all?

  • @skepticmoderate5790

    @skepticmoderate5790

    5 жыл бұрын

    My school teaches C++17. Your school needs to get up to date.

  • @HermanWillems

    @HermanWillems

    5 жыл бұрын

    Do they also teach inheritance ? Likes it's a gift from God? (Rust lang doesn't even have inheritance because it's an anti-pattern)

  • @anicsr
    @anicsr6 жыл бұрын

    I've never watched a better quality tutorial series than this. Thank you so much for making these, cheers!

  • @alexwhite6133
    @alexwhite61336 жыл бұрын

    Great, finally one who explains everything comprehensibly! Thanks for the effort!

  • @elgs1980
    @elgs19805 жыл бұрын

    OMG! Cherno! You make these things so clear that takes other teachers forever to explain.

  • @marcusk7855
    @marcusk78553 жыл бұрын

    I love that idea of implementing stuff in the STL our selves. Great way to learn.

  • @andreypalamarchuk472
    @andreypalamarchuk4724 жыл бұрын

    Thank you. Really good explanation of poiters wrappert under-the-hood.

  • @YoMast3r
    @YoMast3r6 жыл бұрын

    I really enjoyed that one. Really good job, keep it that way!

  • @JannisAdmek
    @JannisAdmek5 жыл бұрын

    thank you for making this high quality, easy to follow videos.

  • @MBBGun14
    @MBBGun146 жыл бұрын

    Hi Cherno, another great video. Although, Im C# programmer, it's good to refresh C++ and learn something new - your channel is perfect place for that. I couldn't resist to become your Patreon, to give you some respect for your work, you earned it ;).

  • 6 жыл бұрын

    Very balanced and unbiased summary, thank you.

  • @IshaanKarnik
    @IshaanKarnik6 жыл бұрын

    Best explanation I have come across so far. Keep up the good work.

  • @DaRealPielover1987
    @DaRealPielover19876 жыл бұрын

    Hey Cherno, I love this series. I think that a topic that would be good to cover since many places don't have a good explanation would be rvalue and lvalue references. This was a major pain point for me when learning c++ but is so integral to the language.

  • @Croccifixo
    @Croccifixo3 жыл бұрын

    Currently taking a distance course at uni on C++, working with smart pointers, and this video gives a much neater explanation tham the course material (which for me is in a language I'm not that good at anyways). This really helped clear up some confusions I had about smart pointers based on the course material, thanks

  • @Weltdrache
    @Weltdrache6 жыл бұрын

    Wow really good explained and short/fast too! I hope your other videos are as good as this one!

  • @ali-kadar
    @ali-kadar4 жыл бұрын

    Thank you for the explanation. It was very well and succinctly explained.

  • @shadowwalker23901
    @shadowwalker239016 жыл бұрын

    You can make a shared_ptr from a unique_ptr. Using assignment AKA the = operator or std::move(). This make it convent to return a unique_ptr and let the caller determine if they want it to be a shared_ptr or not.

  • @faizydeveloper
    @faizydeveloper3 күн бұрын

    Very informative video. I am C# unity game developer but when I KZread search Stack vs Heap I found one of video on it. It was so informative so I decided to watch full playlist and now I am on 43 video.

  • @robertalaverdyan3150
    @robertalaverdyan31504 жыл бұрын

    Good job. Seems like this dude really knows what he is talking about. I would like to see more videos with some of the most frequently asked interview questions discussed.

  • @Xxp0r
    @Xxp0r4 жыл бұрын

    Hey Cherno, re-watching your series as they're always a good refresher. Will, you ever do a video about 3:23 talking about exceptions and why you don't like them?

  • @bisalonggoplays2819
    @bisalonggoplays28193 жыл бұрын

    Wow, this video shot smart pointers straight into my brain and it didn't even need to write keywords or show diagrams on it. Awesome vid, Cherno ~

  • @sankar9483
    @sankar94835 жыл бұрын

    Amazing video. Nice coverage on smart ptr. Looking forward more :)

  • @ishgirwan
    @ishgirwan6 жыл бұрын

    Thanks..as usual looking forward for future videos :) Will it be possible for you to create a video which explains how c++ 98/11/14/17 are different from each other and how newer versions are better. Thanks again.

  • @WizardofWestmarch
    @WizardofWestmarch6 жыл бұрын

    Might've been worth mentioning how move semantics work with Unique_ptr since that seems to be part of what can make them useful (still getting back up to speed on the language after a lot of time in C#, which your videos are helping with a ton).

  • @callmejobson
    @callmejobsonАй бұрын

    Making my way through this series!! Im taking notes as well thanks again Cherno!

  • @cristianotubeful
    @cristianotubeful5 жыл бұрын

    Nice video and good explanation. I appreciate your effort and encourage you to keep it up!

  • @sammyj29
    @sammyj29 Жыл бұрын

    I wish I had found this channel earlier. Loving the videos and the crisp explanation!!

  • @SteveAdamRocks
    @SteveAdamRocks Жыл бұрын

    Thanks for the video. All your teachings are top notch. There's a reason why you show up first when researching a c++ topic.

  • @bumate90
    @bumate906 жыл бұрын

    Wow dude! Great video, very precise. Keep up the good work! ;)

  • @HazemSaleh
    @HazemSaleh6 жыл бұрын

    Excellent man, thanks for your explanation.

  • @habibyama
    @habibyama6 жыл бұрын

    Amaznig job Cherno, You nailed it :)

  • @certainly_unsure
    @certainly_unsure6 жыл бұрын

    The best C++ video series ever. This man is awesome.

  • @greatbullet7372
    @greatbullet73726 жыл бұрын

    This wasnt enought Cherno for my Opinion, please make more videos. They are awesome

  • @jakubfraczek1208
    @jakubfraczek12082 жыл бұрын

    Surprisingly I understood everything, very clear explanation!

  • @AndrewMelnychuk0seen
    @AndrewMelnychuk0seen3 жыл бұрын

    Hey this was an excellent explanation on the topic! Thanks a lot.

  • @mytech6779
    @mytech67796 жыл бұрын

    It was more than a bit over my skill level, but I recently watched a cppcon talk on smart pointers and the examples they used involved crazy data structures generated from meta-programming templates and whatnot. Basically in those cases the smart pointers were helping to prevent unintentionally created circular structures from creating some sort of memory leaking dead-lock issue in programs with long run times.(server farm type software; not really an issue in most games I imagine.)

  • @groberti
    @groberti5 жыл бұрын

    Such clear explanation, kudos

  • @loque26
    @loque264 жыл бұрын

    Thanks for explaining this so well.

  • @kylefillingim9658
    @kylefillingim96585 жыл бұрын

    I love how the your code has a large enough text size that I can read it, even without full screening the video thanks for this. the garbage collector is one of the biggest reasons I stooped using c++ 10 years ago and switched to c#

  • @mryup6100

    @mryup6100

    4 жыл бұрын

    I've heard bad things about using garbage collector, but I have never used it myself as I am fairly new to the c++ language.

  • @khatharrmalkavian3306

    @khatharrmalkavian3306

    2 жыл бұрын

    @@mryup6100 He means the C# collector, I believe. C++ does not have a standard GC.

  • @mountgraph1403
    @mountgraph14036 жыл бұрын

    Thank you man as always awesome !

  • @mattgraves3709
    @mattgraves37093 жыл бұрын

    Damn, I was scrolling ahead in the playlist and you cover all sorts of interesting topics here! Holy smokes...

  • @river6634
    @river66343 жыл бұрын

    Solid explanation. Thank you very much.

  • @chacho1155
    @chacho11552 жыл бұрын

    Awesome explanation! Thank you!

  • @dimbata
    @dimbata4 жыл бұрын

    *std::make_shared is NOT ALWAYS preferred to using "new" to initialize a std::shared_ptr!* Due to the fact that weak pointers need the control block to know whether or not the resource is available, using weak pointers that reference a shared pointer instantiated via make_shared, *WILL* keep the whole controller block from being freed, which includes the memory allocated for the resource, even if the resource has been destructed due to reference counting reaching 0. ---------- *TL;DR* Using std::make_shared means std::weak_ptr *WILL* keep the memory of the resource from being freed. In this case "new" can be used instead of std::make_shared for the instantiation. ---------- That's an old video and you've probably already made a newer one covering this issue, but I thought I'd share this just in case.

  • @justchill99902
    @justchill999022 жыл бұрын

    Thank you :) Such an intimidating topic made looked like a piece of cake. It's been Chernified :D

  • @lewisb8634
    @lewisb86346 жыл бұрын

    I used to be of the mindset that smart pointers were just for people who couldn't be bothered to manually manage memory properly, as if they were a cheap alternative, and I'm glad I'm over that phase now! On top of the advantages you mentioned in this video, I really like them for semantics. Seeing that a dynamically allocated member is a unique_ptr tells me that the parent class will own/be responsible for the object. I still use raw pointers to indicate that a class does not care about owning/managing the pointed-to object, it just wants a brief reference to it (provided that the lifetime of the parent class exceeds that of the object obviously). AFAIK, C++17 is bringing with it the "std::observer_pointer" which is literally just a raw pointer with a more semantically-useful name (whether or not it comes under 'smart' pointer is debatable). It has exactly the same purpose as the raw pointers I use currently and hints that the parent is simply observing the object. Anyway awesome video as usual Cherno, keep up the amazing content! :)

  • @J.D-g8.1

    @J.D-g8.1

    Жыл бұрын

    Yes i was disinterested in smart pointers myself for a long time. But they are very useful not just for memory leaks, but also for the fact that implicit moves can happen very easily. So when you care about ownership/storage they can really be a great help to find/avoid bugs.

  • @kpopisthebestful
    @kpopisthebestful4 жыл бұрын

    Explained marvelously

  • @PandeyRaj
    @PandeyRaj6 жыл бұрын

    Hi from India , One of the best video series of c++ , straight to point. Thanks for sharing information. Also i'll request you to start a java or any other language/ series too. Thanks again .

  • @enricosaccheggiani3192
    @enricosaccheggiani31924 жыл бұрын

    thanks so much your video on smart pointers is very useful and interessant . All the best regards

  • @vinothbose
    @vinothbose3 жыл бұрын

    Very good explanation. Short and sweet

  • @user-vs6kl8ph5v
    @user-vs6kl8ph5v Жыл бұрын

    you've explained the essence of the topic in literally several short sentences, this is immediate subscription + notifications on + lifetime respect from me

  • @user-vs6kl8ph5v

    @user-vs6kl8ph5v

    Жыл бұрын

    and you're handsome :)

  • @mihaicraciun8678
    @mihaicraciun86788 ай бұрын

    This cleared up things a lot, thank you!

  • @AmericaAndAllies
    @AmericaAndAllies4 жыл бұрын

    Excellent introduction. Thanks.

  • @jmokut
    @jmokut Жыл бұрын

    great concise explanation!

  • @mokbelkaram9113
    @mokbelkaram91134 жыл бұрын

    I really like your videos! Can you make a playlist about design patterns in c++ ?

  • @krlozadan1586
    @krlozadan15866 жыл бұрын

    Great video man! Thanks

  • @TarunKumarSaraswat
    @TarunKumarSaraswat4 жыл бұрын

    Great examples & explanation

  • @007hunting
    @007hunting3 жыл бұрын

    @thecherno loved all videos of C++ series

  • @martintourangeau4882
    @martintourangeau48822 жыл бұрын

    Très bien expliqué, bravo !

  • @justind6983
    @justind69836 жыл бұрын

    First question I had was is this in a playlist...(few moments later) thank you sir, you have a new sub :)

  • @justind6983

    @justind6983

    6 жыл бұрын

    Pointers in C++ and Java in the simplest form are easy for me to understand. But once people start using them beyond the basics... I quickly am lost in the sauce :(

  • @Kapil_Thakar
    @Kapil_Thakar Жыл бұрын

    Great and to the point explanation.. Love it...

  • @mcjustin1
    @mcjustin13 жыл бұрын

    Pointers are still such an issue for me. So cool to see all these various objects discussed in ways I never see brought up on courses.

  • @Texas-Manager
    @Texas-Manager2 жыл бұрын

    What a pretty course about Smart pointer! Thanks

  • @Anonymous-ym6st
    @Anonymous-ym6st3 ай бұрын

    Really awesome video!!! Easy to understand with good examples! But did I miss it or anyone else find the video about implementing these unique_ptr / shared_ptr later in the playlist or other places?

  • @trantrungkien2790
    @trantrungkien2790 Жыл бұрын

    thank you! easy to understand

  • @rcookie5128
    @rcookie51284 жыл бұрын

    One of my favorite videos to date! :)

  • @MSP_-wp5fb
    @MSP_-wp5fb3 жыл бұрын

    This guy basically taught me my advanced prog module better than my lecturer. Did well on my exam today all thanks to the Cherno

  • @annahakobian7371
    @annahakobian73715 жыл бұрын

    Thank you man!!

  • @IndependentSpirit1923
    @IndependentSpirit19234 жыл бұрын

    Very cool video dude. Well explained.

  • @shizhouliu4131
    @shizhouliu41312 жыл бұрын

    Your C++ series make me feel C++ is lovely. :)

  • @jimba6486
    @jimba64863 жыл бұрын

    I was lucky to have Professor in data structures who taught as hobby and was a VP of a start up. He taught us modern c++ practiced today. Incorporated C++11 to C++17 features. He is a gem because I hear a lot of people learning C in college, with little to no strong OOP fundamentals

  • @marcs9451

    @marcs9451

    Жыл бұрын

    C or a C-style C++ is actually better for explaining datastructures, it doesnt rely on OOP and gives insight into how memory is managed. C++ with smart pointers or Java/C# being used for this leaves a hole in the student's mind about proper resiurce management

  • @jonf6509
    @jonf65093 жыл бұрын

    10:46 what you need is like some kind of smart pointer so that you can dynamically point to where youtube moves the like button

  • @yabastacode7719
    @yabastacode77196 жыл бұрын

    Hey cherno, I am a new subscriber and I love your serie in c++ tank you. I just want you to talk about design patterns in c++ and give us some advices about them should we use them on our code or not.

  • @gauravmehta888
    @gauravmehta8884 жыл бұрын

    Cool .. very clearly explained .. but i wish u could mention circular dependency issue with shared_ptr.

  • @user-kb8im6ov8p
    @user-kb8im6ov8p Жыл бұрын

    smart ptr is so charming bro,a great invention of modern c plus plus.And this lesson is so sick!

  • @madhurimaburagohain7438
    @madhurimaburagohain74386 жыл бұрын

    Hello , thank you so much. You have saved me..waiting for more videos...if you are familiar with ns3 simulator, please upload some videos

  • @omriz6909
    @omriz69093 жыл бұрын

    Extremely helpful video!

  • @sajin1kolappan
    @sajin1kolappan4 жыл бұрын

    Great Explanation

  • @crusaderanimation6967
    @crusaderanimation6967 Жыл бұрын

    Ngl at first a kinda liked the idea of managing your memory yourself with new & delet "Real men style" but when i grasped what unique_ptr dose it started to love it ! And now i know what shared_ptr and weak_ptr dose too.

  • @charry23fercho
    @charry23fercho Жыл бұрын

    You're the best youtuber professor in C++. Best regards

  • @miguelfernandosilvacastron3279
    @miguelfernandosilvacastron32796 жыл бұрын

    Very good explanatory video.

  • @kartikshrivastava1500
    @kartikshrivastava15004 жыл бұрын

    One thing which I'd like to add is, we can transfer the ownership of unique_ptr with std::move function. After doing that newly created unique_ptr will be pointing to the container pointer by old unique_ptr, and thus old unique_ptr will point to null.

  • @jjp8710
    @jjp87103 жыл бұрын

    Love your channel, clear and concise. It would be great if you can give good example where it is preferred to just use 'new ' and 'delete' instead of smart pointers . Thanks!

  • @khatharrmalkavian3306

    @khatharrmalkavian3306

    2 жыл бұрын

    When writing custom allocators, or in those somewhat rare cases when you have to work with an external library that insists on doing its own memory management, but wants you to hand it allocated objects. (There are all kinds of really horrible libraries out there.)

  • @chifaabouguila2682
    @chifaabouguila26824 жыл бұрын

    thxxxx for this awesome tutorials

  • @michaelstrauss8066
    @michaelstrauss80664 жыл бұрын

    Thank you for helping me relearning C++

  • @daSurrealist
    @daSurrealist4 жыл бұрын

    crisp and clear

  • @naveensenapati9032
    @naveensenapati903211 ай бұрын

    Im 5 years late to this video 😢. You changed my whole perspective on them thank you.

  • @broken_abi6973
    @broken_abi69735 жыл бұрын

    I think you should have emphasized that you can pass a unique_ptr by reference to a function or move it. The latter is really important when you want to put an object with a unique_ptr inside an STL container.

  • @WarrenMarshallBiz
    @WarrenMarshallBiz4 жыл бұрын

    Perfect explanation, thanks so much!

  • @bumbarabun

    @bumbarabun

    4 жыл бұрын

    Unfortunately it is not perfect and explains it on wrong level IMHO - too simplified. You need to explain what ownership means and how using smart pointers make your program cleaner and more readable.

  • @WarrenMarshallBiz

    @WarrenMarshallBiz

    4 жыл бұрын

    @@bumbarabun *shrug* I dunno, works for me!

  • @michaeljonez4199
    @michaeljonez41994 жыл бұрын

    awesome vid! I can't bring myself to used smart pointers, personally. I just leave a comment "this is handled in destructor" or something. but I see their value, especially on large, corporate projects.

  • @khatharrmalkavian3306

    @khatharrmalkavian3306

    2 жыл бұрын

    This comment hurts me physically.

  • @JoshuaKisb
    @JoshuaKisb6 жыл бұрын

    AWESOME VIDEO. ur the best.

  • @bebel4298
    @bebel42983 жыл бұрын

    It's my fourth time watching this video. Satisfied, as always.

  • @AlexTilkin
    @AlexTilkin5 жыл бұрын

    Great job!

  • 4 жыл бұрын

    I love your face palms, I do the same when someone comes with these arguments.

  • @AyushKumar-fk5lm
    @AyushKumar-fk5lm2 жыл бұрын

    Awesomeeeee. Worth so much knowledge. Would be so nice if you had a series on Java too :p

  • @paulozhang9346
    @paulozhang93463 жыл бұрын

    What an awesome tutorial.

  • @benjaminf.3760
    @benjaminf.37605 жыл бұрын

    Dude your videos are THE SHIT!!! Thanks so much, keep going