Тёмный

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

The Cherno
Подписаться 645 тыс.
Просмотров 668 тыс.
50% 1

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

Опубликовано:

 

2 июл 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 554   
@cpdorli
@cpdorli 6 лет назад
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 4 года назад
Agrreed
@amp2amp800
@amp2amp800 3 года назад
That's exactly what I like too!
@anmararw
@anmararw Год назад
Definitely
@zanagi
@zanagi 7 месяцев назад
6 years later, also yes
@theleopeople5771
@theleopeople5771 18 дней назад
he made me become gay
@peligros13
@peligros13 2 года назад
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 11 месяцев назад
Thx. This helps a lot.
@ObsessiveClarity
@ObsessiveClarity 7 месяцев назад
LOL better organized / more concise summary in a youtube comment than in any article ive seen. Thank u
@leixun
@leixun 4 года назад
*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 4 года назад
@Lei Xun Thanks mate
@rishitsingh6621
@rishitsingh6621 4 года назад
Thanks a lot, again
@leixun
@leixun 4 года назад
@@rishitsingh6621 You are welcome
@minoset6037
@minoset6037 Год назад
sex
@everettmthunzi
@everettmthunzi 3 года назад
These are no mere tutorials ... no, my good friends, these are timeless works of art! Your work is much appreciated!
@erawanthewise8227
@erawanthewise8227 2 года назад
>>
@LucidStew
@LucidStew 6 лет назад
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
@anicsr 6 лет назад
I've never watched a better quality tutorial series than this. Thank you so much for making these, cheers!
@elgs1980
@elgs1980 5 лет назад
OMG! Cherno! You make these things so clear that takes other teachers forever to explain.
@alexwhite6133
@alexwhite6133 6 лет назад
Great, finally one who explains everything comprehensibly! Thanks for the effort!
@DaRealPielover1987
@DaRealPielover1987 6 лет назад
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.
6 лет назад
Very balanced and unbiased summary, thank you.
@lewisb8634
@lewisb8634 6 лет назад
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.
@JannisAdmek
@JannisAdmek 5 лет назад
thank you for making this high quality, easy to follow videos.
@dimbata
@dimbata 4 года назад
*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.
@marcusk7855
@marcusk7855 4 года назад
I love that idea of implementing stuff in the STL our selves. Great way to learn.
@YoMast3r
@YoMast3r 6 лет назад
I really enjoyed that one. Really good job, keep it that way!
@MBBGun14
@MBBGun14 6 лет назад
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 ;).
@IshaanKarnik
@IshaanKarnik 6 лет назад
Best explanation I have come across so far. Keep up the good work.
@andreypalamarchuk472
@andreypalamarchuk472 4 года назад
Thank you. Really good explanation of poiters wrappert under-the-hood.
@Croccifixo
@Croccifixo 3 года назад
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
@Xxp0r
@Xxp0r 4 года назад
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?
@groberti
@groberti 5 лет назад
Such clear explanation, kudos
@Weltdrache
@Weltdrache 6 лет назад
Wow really good explained and short/fast too! I hope your other videos are as good as this one!
@habibyama
@habibyama 6 лет назад
Amaznig job Cherno, You nailed it :)
@ali-kadar
@ali-kadar 4 года назад
Thank you for the explanation. It was very well and succinctly explained.
@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.
@HazemSaleh
@HazemSaleh 6 лет назад
Excellent man, thanks for your explanation.
@certainly_unsure
@certainly_unsure 6 лет назад
The best C++ video series ever. This man is awesome.
@bisalonggoplays2819
@bisalonggoplays2819 3 года назад
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 ~
@mountgraph1403
@mountgraph1403 6 лет назад
Thank you man as always awesome !
@sankar9483
@sankar9483 5 лет назад
Amazing video. Nice coverage on smart ptr. Looking forward more :)
@robertalaverdyan3150
@robertalaverdyan3150 4 года назад
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.
@kpopisthebestful
@kpopisthebestful 4 года назад
Explained marvelously
@loque26
@loque26 4 года назад
Thanks for explaining this so well.
@callmejobson
@callmejobson 3 месяца назад
Making my way through this series!! Im taking notes as well thanks again Cherno!
@chacho1155
@chacho1155 2 года назад
Awesome explanation! Thank you!
@krlozadan1586
@krlozadan1586 6 лет назад
Great video man! Thanks
@AmericaAndAllies
@AmericaAndAllies 5 лет назад
Excellent introduction. Thanks.
@jakubfraczek1208
@jakubfraczek1208 3 года назад
Surprisingly I understood everything, very clear explanation!
@river6634
@river6634 3 года назад
Solid explanation. Thank you very much.
@shadowwalker23901
@shadowwalker23901 6 лет назад
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.
@trantrungkien2790
@trantrungkien2790 Год назад
thank you! easy to understand
@vinothbose
@vinothbose 3 года назад
Very good explanation. Short and sweet
@sammyj29
@sammyj29 Год назад
I wish I had found this channel earlier. Loving the videos and the crisp explanation!!
@cristianotubeful
@cristianotubeful 5 лет назад
Nice video and good explanation. I appreciate your effort and encourage you to keep it up!
@martintourangeau4882
@martintourangeau4882 3 года назад
Très bien expliqué, bravo !
@kylefillingim9658
@kylefillingim9658 5 лет назад
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.
@jmokut
@jmokut 2 года назад
great concise explanation!
@mihaicraciun8678
@mihaicraciun8678 9 месяцев назад
This cleared up things a lot, thank you!
@greatbullet7372
@greatbullet7372 6 лет назад
This wasnt enought Cherno for my Opinion, please make more videos. They are awesome
@TarunKumarSaraswat
@TarunKumarSaraswat 4 года назад
Great examples & explanation
@AndrewMelnychuk0seen
@AndrewMelnychuk0seen 3 года назад
Hey this was an excellent explanation on the topic! Thanks a lot.
@bumate90
@bumate90 6 лет назад
Wow dude! Great video, very precise. Keep up the good work! ;)
@naveensenapati9032
@naveensenapati9032 Год назад
Im 5 years late to this video 😢. You changed my whole perspective on them thank you.
@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 :)
@Kapil_Thakar
@Kapil_Thakar 2 года назад
Great and to the point explanation.. Love it...
@annahakobian7371
@annahakobian7371 5 лет назад
Thank you man!!
@miguelfernandosilvacastron3279
Very good explanatory video.
@rcookie5128
@rcookie5128 4 года назад
One of my favorite videos to date! :)
@WizardofWestmarch
@WizardofWestmarch 6 лет назад
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).
@sajin1kolappan
@sajin1kolappan 4 года назад
Great Explanation
@charry23fercho
@charry23fercho Год назад
You're the best youtuber professor in C++. Best regards
@omriz6909
@omriz6909 3 года назад
Extremely helpful video!
@justind6983
@justind6983 6 лет назад
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 :(
@ishgirwan
@ishgirwan 6 лет назад
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.
@justchill99902
@justchill99902 2 года назад
Thank you :) Such an intimidating topic made looked like a piece of cake. It's been Chernified :D
@IndependentSpirit1923
@IndependentSpirit1923 4 года назад
Very cool video dude. Well explained.
@007hunting
@007hunting 3 года назад
@thecherno loved all videos of C++ series
@MSP_-wp5fb
@MSP_-wp5fb 3 года назад
This guy basically taught me my advanced prog module better than my lecturer. Did well on my exam today all thanks to the Cherno
@Texas-Manager
@Texas-Manager 2 года назад
What a pretty course about Smart pointer! Thanks
@JoshuaKisb
@JoshuaKisb 6 лет назад
AWESOME VIDEO. ur the best.
@mattgraves3709
@mattgraves3709 3 года назад
Damn, I was scrolling ahead in the playlist and you cover all sorts of interesting topics here! Holy smokes...
@shizhouliu4131
@shizhouliu4131 2 года назад
Your C++ series make me feel C++ is lovely. :)
@PandeyRaj
@PandeyRaj 6 лет назад
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 .
@faizydeveloper
@faizydeveloper Месяц назад
Very informative video. I am C# unity game developer but when I RU-vid 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.
@daSurrealist
@daSurrealist 5 лет назад
crisp and clear
@enricosaccheggiani3192
@enricosaccheggiani3192 4 года назад
thanks so much your video on smart pointers is very useful and interessant . All the best regards
@visuallization
@visuallization Год назад
So good!
@jonf6509
@jonf6509 3 года назад
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
@user-kb8im6ov8p
@user-kb8im6ov8p Год назад
smart ptr is so charming bro,a great invention of modern c plus plus.And this lesson is so sick!
@mytech6779
@mytech6779 6 лет назад
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.)
@chifaabouguila2682
@chifaabouguila2682 4 года назад
thxxxx for this awesome tutorials
@jimba6486
@jimba6486 3 года назад
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
@nobody2937
@nobody2937 4 года назад
Extremely clear 😊😊😊👍👍👍
@paulozhang9346
@paulozhang9346 3 года назад
What an awesome tutorial.
@AlexTilkin
@AlexTilkin 5 лет назад
Great job!
@mksagal
@mksagal 6 лет назад
Hey Cherno Stroustrup, master of C++. I want to be your apprentice.
@rcookie5128
@rcookie5128 4 года назад
Blasphemy! We're unworthy!! D: /s
@eurko111
@eurko111 4 года назад
@@rcookie5128 XD
@WarrenMarshallBiz
@WarrenMarshallBiz 4 года назад
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!
@jackle3002
@jackle3002 2 года назад
youre a champ cherno
@michaelstrauss8066
@michaelstrauss8066 4 года назад
Thank you for helping me relearning C++
@ashwathyanil1937
@ashwathyanil1937 4 года назад
Awesome video
@ProfessorWaltherKotz
@ProfessorWaltherKotz 6 лет назад
Great video.
@K3rhos
@K3rhos 14 дней назад
I already knew about unique_ptr and shared_ptr, but always was confused about weak_ptr because I never really had a use case, thanks for the clarification !
@h.hristov
@h.hristov 6 лет назад
Thank you :)
@mcjustin1
@mcjustin1 3 года назад
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.
@filipmistrik6465
@filipmistrik6465 5 лет назад
great vid, thx
@bebel4298
@bebel4298 3 года назад
It's my fourth time watching this video. Satisfied, as always.
@mokbelkaram9113
@mokbelkaram9113 4 года назад
I really like your videos! Can you make a playlist about design patterns in c++ ?
@jjp8710
@jjp8710 4 года назад
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.)
@Anonymous-ym6st
@Anonymous-ym6st 5 месяцев назад
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?
@madhurimaburagohain7438
@madhurimaburagohain7438 6 лет назад
Hello , thank you so much. You have saved me..waiting for more videos...if you are familiar with ns3 simulator, please upload some videos
Далее
Copying and Copy Constructors in C++
20:52
Просмотров 421 тыс.
Stack vs Heap Memory in C++
19:31
Просмотров 555 тыс.
It was like a real simulation👩🏻‍💻
00:15
Просмотров 1,9 млн
are "smart pointers" actually smart?
9:44
Просмотров 71 тыс.
unique_ptr: C++'s simplest smart pointer
11:54
Просмотров 40 тыс.
Master Pointers in C:  10X Your C Coding!
14:12
Просмотров 285 тыс.
Dynamic Arrays in C++ (std::vector)
14:14
Просмотров 372 тыс.
SMART POINTERS in C++ (for beginners in 20 minutes)
24:32
POINTERS in C++
16:59
Просмотров 1 млн
31 nooby C++ habits you need to ditch
16:18
Просмотров 736 тыс.
Function Pointers in C++
12:41
Просмотров 382 тыс.
SINGLETONS in C++
19:16
Просмотров 195 тыс.
It was like a real simulation👩🏻‍💻
00:15
Просмотров 1,9 млн