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.
*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
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#
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.
@@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.
@@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?
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?
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.
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
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
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! :)
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.
Very informative video. I am C# unity game developer but when I TH-cam 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.
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
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.)
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 !
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.
*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.
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.
you've explained the essence of the topic in literally several short sentences, this is immediate subscription + notifications on + lifetime respect from me
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).
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.
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.
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 ;).
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?
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.
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!
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.)
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 .
Fairly short and clear explanation. The short message is, I think, to use smart pointers only, unless you have to deal with some older code. That said, I don't like the verbosity of using them. I wish there was something between this and the awfulness of pointer syntax (the star). They decided to expand the language through the standard library rather than the language itself to keep the backwards compatibility, and I understand that attitude, but it can get kind of ugly, especially when there are templates involved. And while they don't want to continue the awful abbreviations that were so common in C, there are still tendencies - in this case "ptr" for pointer. And apparently, they think function names should use underscores rather than camel case. These things seem a bit unnecessary. I wish someone would take the current accumulated wisdom and best practice in C++ and create a whole new (cleaner) language based on that, while getting rid of the bad stuff. To better compete with other popular languages, perhaps they could also make some of the more rigid syntax optional.
@Peterolen It's about semantics and showing intent, which is always good. If you don't care about ownership, there's weak_ptr. The problem isn't just underscores, but that you "have to" type a lot, namespace included. With raw pointers and references, you type one single character. The problem there is that the same symbols mean different things in different places. So I just wish there was a slightly more minimalist and elegant syntax than smart pointers have, but I don't know what that would be. (yes, you could use aliases)
In case you need to refresh your memory on why you should use pointers. "We use pointers because it's easier to give someone an address to your home than to give a copy of your home to everyone".
Shared and weak pointers are unfortunately double the size and they also have a control block. Also If you don't use make_shared you end up doing a two part allocation which slows things down. Finally you have to be careful you don't end up with more than one control block if you are also passing raw pointers around. All these problems can be taken care of if you use your own pointer system and and put the reference count in a base class. I personally think it's a way better solution for most stuff. Like most standard library stuff, it works but sometimes it's sub-optimal.
The overhead of smart pointers is usually negligible to the system call used to allocate memory and negligible to the time wasted on debugging a memory leak.
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 :(
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.
Anyone here read "C++ for Real Programmers" by Jeff Alger? The book introduces a structure called the "Brilliant Pointer." I recommend that Cherno (I mean no disrespect in addressing him thus familiarly) give a lecture on these.
Acabei de ver o vídeo e vou fazer um adendo de uma coisa que ele não demonstrou! Uma coisa interessante que shared_ptr faz que new e delete faz "errado": Se você vai usar polimorfismo e guarda ponteiro da classe genérica apontando pra objetos da classe especializada, quando você chama delete você chama o destrutor APENAS da classe genérica! Você teria que fazer dynamic_cast porque ele não apaga certo! Já se você usar make_shared do shared_ptr, você "guarda" o tipo do objeto apontado pelo ponteiro inteligente! Desse modo, quando sai do escopo ele chama o destrutor da classe especializada *E* da classe genérica em seguida! Uma grande ajuda contra memory leak! By professor de faculdade, não meu.
shared_ptr has a small performance hit, even unique_ptr has a small performance hit, but I think they're definitely worth it to be used all the time. Iv'e been programming C++ for more than 15 years and know new and delete well. One thing I learned in this time is that humans will eventually make mistakes and computers are really powerful and never make mistakes. So I came to a conclusion that I should use every available tool there is to make guarantees that my code works proper. Why ever worry about deleting something when you can almost completely forget about it. So I would advice to never use new and delete (except on your own experimental projects, it's still good to know how they work) and always use unique_ptr if possible, vector for multiple elements, arrays for multiple elements with known lengths and etc, etc...
Summary Smart pointers in C++ automate memory management by automatically deallocating memory when it is no longer needed. Unique pointers are used for exclusive ownership, shared pointers for shared ownership, and weak pointers for non-owning references. They eliminate the need to manually call delete and prevent memory leaks. Highlights 🧠 Smart pointers automate memory management in C++. 🤝 Unique pointers are used for exclusive ownership. 🔄 Shared pointers allow shared ownership and use reference counting. 🙅♂ Weak pointers provide non-owning references and do not increase the reference count. 🚫 Unique pointers cannot be copied to avoid multiple pointers to the same memory.
Watched a lot of this series by now and really enjoy how practical and straightforward your teaching style is, perfect for the post-beginner stage that I am at. Thanks! What do you think about prgramming purists who insist upon C over C++, is that argument valid in any case? Some lecturers on my uni course have that mindset and it feels a little out of touch, both with the requirements of students and of production-level programming (performance not really being the main issue nowadays in most cases). Would you say this series overcomes the criticisms some people have about C++ by teaching 'proper usage'; does C++ functionality generally just have a higher overhead? As a student trying to figure out what best to focus on, I would love to hear your thoughts on this. Again, love the series as I am learning a lot.
The overhead you get with C++ is not even close to languages like Python and Java. C is perfect for low level systems, and high performance libraries. You can't get more performance that that; not even assembly, because compilers are way more smart than humans. You can use C with C++ which hands you the best of both worlds. Or you can try something like Rust.
This is one of the best series about C++. It's clear, it's fast and it has a charming and confident tutor.
Agrreed
That's exactly what I like too!
Definitely
6 years later, also yes
he made me become gay
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.
Thanks for this nice summary!!
wow, I should save this comment
Never too late my friend. Im learning only today - thanks for sharing!
Thx. This helps a lot.
LOL better organized / more concise summary in a youtube comment than in any article ive seen. Thank u
These are no mere tutorials ... no, my good friends, these are timeless works of art! Your work is much appreciated!
>>
I've never watched a better quality tutorial series than this. Thank you so much for making these, cheers!
*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
@Lei Xun
Thanks mate
Thanks a lot, again
@@rishitsingh6621 You are welcome
sex
Im 5 years late to this video 😢.
You changed my whole perspective on them thank you.
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#
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.
@@mryup6100 He means the C# collector, I believe. C++ does not have a standard GC.
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.
Thanks for the video. Didn't get smart pointers in any of my C++ classes since colleges still teach C++98 :\
@@DelicueMusic they usually still use NULL instead of nullptr, so yeah...
@@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.
@@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?
My school teaches C++17. Your school needs to get up to date.
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)
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?
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.
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
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
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
I actually had a c class before an OOP class, and only just now started with the c++ class
I love that idea of implementing stuff in the STL our selves. Great way to learn.
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! :)
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.
Very informative video. I am C# unity game developer but when I TH-cam 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.
OMG! Cherno! You make these things so clear that takes other teachers forever to explain.
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
You're the best youtuber professor in C++. Best regards
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.)
Thanks for the video.
All your teachings are top notch.
There's a reason why you show up first when researching a c++ topic.
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 !
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.
*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.
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.
Im working on creating a chunk system currently and understanding these smart pointers is so useful, thank you!
you've explained the essence of the topic in literally several short sentences, this is immediate subscription + notifications on + lifetime respect from me
and you're handsome :)
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).
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.
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.
Very balanced and unbiased summary, thank you.
This guy basically taught me my advanced prog module better than my lecturer. Did well on my exam today all thanks to the Cherno
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 ;).
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?
Thank you. Really good explanation of poiters wrappert under-the-hood.
Cool .. very clearly explained .. but i wish u could mention circular dependency issue with shared_ptr.
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.
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.
I wish I had found this channel earlier. Loving the videos and the crisp explanation!!
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!
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.)
Making my way through this series!! Im taking notes as well thanks again Cherno!
Those hand gestures are crazy
smart ptr is so charming bro,a great invention of modern c plus plus.And this lesson is so sick!
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 ~
Most concise/clear C++.
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 .
This wasnt enought Cherno for my Opinion, please make more videos. They are awesome
Fairly short and clear explanation. The short message is, I think, to use smart pointers only, unless you have to deal with some older code. That said, I don't like the verbosity of using them. I wish there was something between this and the awfulness of pointer syntax (the star).
They decided to expand the language through the standard library rather than the language itself to keep the backwards compatibility, and I understand that attitude, but it can get kind of ugly, especially when there are templates involved. And while they don't want to continue the awful abbreviations that were so common in C, there are still tendencies - in this case "ptr" for pointer. And apparently, they think function names should use underscores rather than camel case. These things seem a bit unnecessary. I wish someone would take the current accumulated wisdom and best practice in C++ and create a whole new (cleaner) language based on that, while getting rid of the bad stuff. To better compete with other popular languages, perhaps they could also make some of the more rigid syntax optional.
@Peterolen It's about semantics and showing intent, which is always good. If you don't care about ownership, there's weak_ptr.
The problem isn't just underscores, but that you "have to" type a lot, namespace included. With raw pointers and references, you type one single character. The problem there is that the same symbols mean different things in different places. So I just wish there was a slightly more minimalist and elegant syntax than smart pointers have, but I don't know what that would be. (yes, you could use aliases)
Surprisingly I understood everything, very clear explanation!
The best C++ video series ever. This man is awesome.
In case you need to refresh your memory on why you should use pointers.
"We use pointers because it's easier to give someone an address to your home than to give a copy of your home to everyone".
So dope!
Shared and weak pointers are unfortunately double the size and they also have a control block. Also If you don't use make_shared you end up doing a two part allocation which slows things down. Finally you have to be careful you don't end up with more than one control block if you are also passing raw pointers around.
All these problems can be taken care of if you use your own pointer system and and put the reference count in a base class. I personally think it's a way better solution for most stuff. Like most standard library stuff, it works but sometimes it's sub-optimal.
thank you for making this high quality, easy to follow videos.
Hey Cherno Stroustrup, master of C++. I want to be your apprentice.
Blasphemy! We're unworthy!! D: /s
@@rcookie5128 XD
The overhead of smart pointers is usually negligible to the system call used to allocate memory and negligible to the time wasted on debugging a memory leak.
It's possible to cause a train wreck using shared_ptr poorly, but unique_ptr is virtually gratis on modern compilers.
best c++ tutorials of the world
Damn, I was scrolling ahead in the playlist and you cover all sorts of interesting topics here!
Holy smokes...
Great, finally one who explains everything comprehensibly!
Thanks for the effort!
Very good explanation. Short and sweet
Your C++ series make me feel C++ is lovely. :)
Wow really good explained and short/fast too! I hope your other videos are as good as this one!
@thecherno loved all videos of C++ series
First question I had was is this in a playlist...(few moments later) thank you sir, you have a new sub :)
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 :(
A nice video, mentioning move-semantics would have been nice, but perhaps too much for one topic. Is there another video for this?
Thank you for helping me relearning C++
Best explanation I have come across so far. Keep up the good work.
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.
This comment hurts me physically.
What a pretty course about Smart pointer! Thanks
I really like this useful content as a programmer .
Extremely good explanation even in 2022.
Please complete the series of STL containers. how to select which container to use and why?
Anyone here read "C++ for Real Programmers" by Jeff Alger? The book introduces a structure called the "Brilliant Pointer." I recommend that Cherno (I mean no disrespect in addressing him thus familiarly) give a lecture on these.
Acabei de ver o vídeo e vou fazer um adendo de uma coisa que ele não demonstrou!
Uma coisa interessante que shared_ptr faz que new e delete faz "errado":
Se você vai usar polimorfismo e guarda ponteiro da classe genérica apontando pra objetos da classe especializada, quando você chama delete você chama o destrutor APENAS da classe genérica! Você teria que fazer dynamic_cast porque ele não apaga certo! Já se você usar make_shared do shared_ptr, você "guarda" o tipo do objeto apontado pelo ponteiro inteligente! Desse modo, quando sai do escopo ele chama o destrutor da classe especializada *E* da classe genérica em seguida! Uma grande ajuda contra memory leak! By professor de faculdade, não meu.
Thanks. Valeu!
I'm glad you facepalmed at 7:07 to really drive home your disappointment in my demographic. Almost made me rethink my ways.
A hint on why not using auto_ptr could be cool :-). Nice video anyways !
Explained marvelously
This cleared up things a lot, thank you!
Such clear explanation, kudos
shared_ptr has a small performance hit, even unique_ptr has a small performance hit, but I think they're definitely worth it to be used all the time.
Iv'e been programming C++ for more than 15 years and know new and delete well. One thing I learned in this time is that humans will eventually make mistakes and computers are really powerful and never make mistakes. So I came to a conclusion that I should use every available tool there is to make guarantees that my code works proper. Why ever worry about deleting something when you can almost completely forget about it.
So I would advice to never use new and delete (except on your own experimental projects, it's still good to know how they work) and always use unique_ptr if possible, vector for multiple elements, arrays for multiple elements with known lengths and etc, etc...
std::unique_ptr has no performance impact compared to new/delete unless you've disabled optimization entirely.
He is explained in the high level, please refer "Bo Qian" series he explained all the corner cases.
Thanks... for pointing that. Indeed the videos are a bit in depth and clear to understand as well. :)
I really enjoyed that one. Really good job, keep it that way!
I really like your videos! Can you make a playlist about design patterns in c++ ?
great concise explanation!
Very good explanatory video.
Thank you :) Such an intimidating topic made looked like a piece of cake. It's been Chernified :D
@The Cherno, can you do more videos on multi-threading and smart pointers usage.
Hello , thank you so much. You have saved me..waiting for more videos...if you are familiar with ns3 simulator, please upload some videos
For anyone having problems using this code in CodeBlocks just go into Settings>Compiler and in the list below check Have g++ follow the C++14 ISO
Excellent man, thanks for your explanation.
Amaznig job Cherno, You nailed it :)
I love your face palms, I do the same when someone comes with these arguments.
Thank you for the explanation. It was very well and succinctly explained.
Summary
Smart pointers in C++ automate memory management by automatically deallocating memory when it is no longer needed. Unique pointers are used for exclusive ownership, shared pointers for shared ownership, and weak pointers for non-owning references. They eliminate the need to manually call delete and prevent memory leaks.
Highlights
🧠 Smart pointers automate memory management in C++.
🤝 Unique pointers are used for exclusive ownership.
🔄 Shared pointers allow shared ownership and use reference counting.
🙅♂ Weak pointers provide non-owning references and do not increase the reference count.
🚫 Unique pointers cannot be copied to avoid multiple pointers to the same memory.
It's my fourth time watching this video. Satisfied, as always.
Great and to the point explanation.. Love it...
Awesome explanation! Thank you!
Watched a lot of this series by now and really enjoy how practical and straightforward your teaching style is, perfect for the post-beginner stage that I am at. Thanks! What do you think about prgramming purists who insist upon C over C++, is that argument valid in any case? Some lecturers on my uni course have that mindset and it feels a little out of touch, both with the requirements of students and of production-level programming (performance not really being the main issue nowadays in most cases). Would you say this series overcomes the criticisms some people have about C++ by teaching 'proper usage'; does C++ functionality generally just have a higher overhead? As a student trying to figure out what best to focus on, I would love to hear your thoughts on this. Again, love the series as I am learning a lot.
The overhead you get with C++ is not even close to languages like Python and Java.
C is perfect for low level systems, and high performance libraries. You can't get more performance that that; not even assembly, because compilers are way more smart than humans.
You can use C with C++ which hands you the best of both worlds. Or you can try something like Rust.
Great examples & explanation
youre a champ cherno
I'm leaning c++ and your videos are really helpful. May I ask what is the 'overhead' you mean?