Destructors in C++

  Рет қаралды 276,737

The Cherno

The Cherno

Күн бұрын

Twitter ► / thecherno
Instagram ► / thecherno
Patreon ► / thecherno
Slack ► slack.thechern...
Constructors in C++ ► • Constructors in C++
Series Playlist ► • C++
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

Пікірлер: 105
@lobelia5844
@lobelia5844 6 жыл бұрын
Holy shit! Life saviour of a video, lecturers couldn't explain this properly in a 45 minute lecture, forums don't even answer why and when to use a destructor, and here's a short, simple 5 minute video explaining everything! Big props to you!
@exupload93
@exupload93 7 жыл бұрын
I've have this habit now, I see a new video here, I hit the like button before watching since I know before hand this gonna be gud. You are doing a wonderful job! As a frequent C++ user (and I'm sure others alike can relate) even though I know more than the basics, the explanation and pacing of the concepts surrounding the topics in the videos are simple and refreshing to newcomers and regulars alike. Your work is much appreciated , keep up the awesome work good man :)
@ToyReviewsAndUnboxing
@ToyReviewsAndUnboxing 4 жыл бұрын
I did the same exact thing! haha
@abdoelsmahy2962
@abdoelsmahy2962 4 жыл бұрын
Hi Osama! I have n issue with my compiler ,I hope you could help me get ride of it!
@thelowendstudio
@thelowendstudio 3 жыл бұрын
I do the same thing!!!
@caprisundad
@caprisundad Жыл бұрын
same!
@deepwoodsengineering3763
@deepwoodsengineering3763 5 жыл бұрын
Scrolled through your playlist and opened like 20 videos, each into a new tab. Then clicked on each tab to add it to "watch later". Every time I clicked on a new tab your "Hey what's up guys" and the arm across motion way on point lol 😂
@krec348
@krec348 7 жыл бұрын
Wow, i can call the destructor manually, first time i have heard of that haha. Good video!
@PeterPetrakis
@PeterPetrakis 7 жыл бұрын
When you create an object using placement new, the destructor is not automatically run. It's best to be avoided. If your class is a POD you can just memcpy into it. I also suggest static_assert for the expected size of that object. Kinda important with media formats.
@ValentinKunz-d3i
@ValentinKunz-d3i 4 ай бұрын
Noted: - Never create an object of the same class in the destructor Love this playlist, thank you :)
@MartialBarts
@MartialBarts 7 жыл бұрын
Loving the frequency of the videos. Hopefully this can keep up for a while so we can quickly get into the more interesting parts of the language.
@olafk8232
@olafk8232 3 жыл бұрын
I think maybe destructors are more interesting than you think.
@leixun
@leixun 4 жыл бұрын
*My takeaways:* 1. Using destructors to avoid memory leaks 3:05 2. Call destructors manually 3:37
@ghofranetorjmene2960
@ghofranetorjmene2960 Жыл бұрын
In this scenario, the function () is executed within the stack frame. Once the execution is complete, the stack frame is automatically destroyed, eliminating the need for a destructor in this particular case.
@matt-g-recovers
@matt-g-recovers 3 жыл бұрын
Nice and neat, all tidy and clean. Very nice feature
@dxlge
@dxlge Жыл бұрын
notes: The destructor gets called every time a object gets destroyed. The destructor essentially cleans up any memory that we might have used when the object was created. Destructors are really important when we use dynamic memory, we need to make sure that we free up the memory that we allocate on the stack when we use the object.
@typicalretard6968
@typicalretard6968 3 жыл бұрын
man this is the best c++ resource! thank you so much!
@nineteenn7866
@nineteenn7866 2 жыл бұрын
Your tutorials are awesome! May God bless you!
@black_squall
@black_squall 7 жыл бұрын
Would you ever consider making an openGL c++ GUI tutorial series, Cherno? I'm interested in rolling my own for games. With features like sliders and buttons etc. Also some practical examples of how to integrate them into a simple game would be cool.
@SuheybBecerek
@SuheybBecerek 4 жыл бұрын
this series is being very useful. I wish I discovered it when taking C++ class
@cetruonghai
@cetruonghai 3 жыл бұрын
His hair in this episode is perfect :))
@DiegoBM
@DiegoBM 4 жыл бұрын
Minute 1:11, I was just wondering, even if the members are allocated in place, would it not be safer to still set them to zero upon destruction to make sure that you are leaving a clean memory for whichever software uses that memory region next?
@ferociousjuggler2668
@ferociousjuggler2668 4 жыл бұрын
His output Console window is set to automatically close after the program finishes executive, to get around that and prevent hit program from closing suddenly he uses the cin.get()(or getch()) to make the program wait for the user(him) to input a character .. Tldr; getch() needs an input and this keeps the program from ending until he presses a button on his keyboard
@dXXPacmanXXb
@dXXPacmanXXb 7 жыл бұрын
pls make a heap stack tutorial
@TheRojo387
@TheRojo387 2 жыл бұрын
I can tell that destructors in modelling programs run code that saves the uninitialised data, serialised, in an array of previous operations, so that destroyed objects may be restored.
@Steven-tw7iz
@Steven-tw7iz 7 жыл бұрын
Would have liked to see an example with dynamic allocation, but I suppose it would have done been a repeat of stack allocation anyway. I just think lots of examples are great to help people understand better. :) still a fantastic series though! Loving it
@BurgerKingHarkinian
@BurgerKingHarkinian 7 жыл бұрын
Yea, the video would probably have benefited a lot if he made a video about heap vs stack allocation first and picked it up again in this video.
@001mhu
@001mhu 7 жыл бұрын
if it's not too much trouble could you do a video on const? especially its relations with references, references to const, pointers to const, const pointers? I'm going through C++ primer, but have the hardest with them eventhough i know the basics of const, references and pointers :(
@ihnwtpu
@ihnwtpu 7 жыл бұрын
Basically the const always applies to whatever is to the left of it: int * a; // pointer to int int const * a; // pointer to const int int * const a; // const pointer to int int const * const a; // const pointer to const int int & a; // reference to int int const & a; // reference to const int int & const a; // doesn't really make any sense since all references are essentially const There is one exception - when the const is at the beginning: const int * a; // pointer to const int, same as 'int const * a;'
@ZukaBE
@ZukaBE 2 жыл бұрын
thanks goat
@darimuhittin
@darimuhittin 10 ай бұрын
Best course in the whole world !
@Idlecodex
@Idlecodex 5 жыл бұрын
Can you think of any reason to delete the default destructor?
@modernmage
@modernmage Жыл бұрын
You talked a lot about stack allocation but hadn't explained this at all yet...
@sgyffysgyffy4736
@sgyffysgyffy4736 6 жыл бұрын
Great video!
@daniellima3730
@daniellima3730 2 жыл бұрын
Thank you for the examplanation.
@rcookie5128
@rcookie5128 7 жыл бұрын
I always forget to delete my heap allocated stuff, haha memory leaks for the win! ;P Maybe I should keep a list of all objects that I created on the heap, and then delete them from the list when their destructor is called or sth like this..
@Plasticcaz
@Plasticcaz 7 жыл бұрын
Consider looking into std::unique_ptr. It might help you a little (or you may determine that it's more trouble than its worth, but you should still look into it.).
@rcookie5128
@rcookie5128 7 жыл бұрын
will do so thanks! Oh and now I've researched further into all the memory allocation stuff (should've done way earlier to expand my general understanding of c++) and came up to the keywords "malloc" and "free", and that variables that were constructed with "new" (and destroyed with "delete") actually are stored on the "free store". I think I got the idea of the difference between them, but I still would appreciate if Cherno would go into detail on this topic when addressing it in some of the next videos..
@rcookie5128
@rcookie5128 7 жыл бұрын
thanks again! Looked up into it and smart pointers (like the std::unique_ptr or std::shared_ptr) are really interessting. Definetly would try them out if I have a fitting situation
@Xx_McJasper_xX
@Xx_McJasper_xX 3 жыл бұрын
Commenting so KZbin-bot knows I love The Cherno.
@shrivastavakartik3787
@shrivastavakartik3787 6 жыл бұрын
Hey there, thank you so much for these videos... I've a doubt! void Function(){ Entity e; e.~Entity(); e.Print(); //why this line still prints "0, 0" even if we have destroyed the entity???? I guess it should give an error because we //have destroyed the instance. Doesn't it freed the memory allocated to public variables X and Y. }
@shrivastavakartik3787
@shrivastavakartik3787 6 жыл бұрын
@Peterolen Thanks man! for clarifying my doubt.
@praveshgaire3437
@praveshgaire3437 6 жыл бұрын
The destructor was called once when he called it explicitly and then again when the class went out of the scope of the Function() function. Am I right ?
@praveshgaire3437
@praveshgaire3437 6 жыл бұрын
How so? I think its correct
@nonsensetutorials8573
@nonsensetutorials8573 4 жыл бұрын
@Peterolen code is correct
@gtorres94
@gtorres94 Жыл бұрын
Somehow doesn't make sense to me. How can you destroy the same object twice?
@guille_sanchez
@guille_sanchez 6 ай бұрын
​@@gtorres94 Late to the party, but maybe useful for newcomers. You're not destroying the object twice: an instance of an obj can only be destroyed once. If you try to destroy it twice, you'll get a null reference exception. Now, destructors (or destructor functions) are different to Destroy functions. The destroy function destroys the object and can only be run once. The destructor, on the other hand, is an empty function suitable for you to place whatever clean up code you want it to run (if needed) before the object gets destroyed. As so, you can call the destructor function for as many times as you wish, although it wouldn't be so useful. For instance, theoretically you can place a method that plays an audio cue inside the destructor, and call the destructor each time you want to play a sound effect, but please don't do that 😂. Likewise, inside the function that TheCherno wrote where he creates an instance of the Entity class, he can make a loop with 300 iterations in which he can call the destructor, so the destructor will be called (and the log inside printed) 300 times. And only then, when the function returns, A.K.A the stack allocated entity gets out of scope, then the real destroy method for the instantiated object gets automatically triggered and therefore your destructor would be called one last time to do any clean up you are supposed to do, if needed, before the object (and all associated resources) gets gone for good.
@_yeh
@_yeh Жыл бұрын
u can use destructors to create projectiles in games for example spells in albion online, at the end of the projectiles way it has to dissapear
@BAMBAMBAMBAMBAMval
@BAMBAMBAMBAMBAMval Жыл бұрын
Cherno is it possible with "standard" vs settings to compile code with memory leaks or can you be certain you always will get an error when trying to make an exe?
@chainonsmanquants1630
@chainonsmanquants1630 4 жыл бұрын
Thanks
@hattron6704
@hattron6704 2 жыл бұрын
Thank you!
@pratiknvlogs
@pratiknvlogs 2 жыл бұрын
Dear Cherno, which compiler do you use?
@asaherrin4737
@asaherrin4737 3 жыл бұрын
better than my college class
@olafk8232
@olafk8232 3 жыл бұрын
Who calls the destructor (stack object) and who in the case of std::unique_ptr p(new classname());? Do only stack objects have a 'magical' ;-) implicit destructor call?
@olafk8232
@olafk8232 3 жыл бұрын
@Artem Katerynych Thanks Artem, I will study that, I am curious, what std:make_unique exactly does, why is it necessary or handy? My original question was, who triggers the destructor chain e.g. at the end of a function, when the program leaves the function scope. Is that some special compiler "magic"?
@AbdulMoiz-ho8rx
@AbdulMoiz-ho8rx 2 жыл бұрын
Excellent
@wotchadave
@wotchadave 6 жыл бұрын
Thank you for the video, as always very insightful. I do have one quick question: I have an instance which may decide to create new instances based on some condition. If this condition is fulfilled, the original instance would become surplus to requirements. Therefore, in the class method used to define the creation of new instances, could it be worthwhile to include a destructor to delete the original instance *after* it has created the new instances in order to conserve memory?
@dharmanshah1239
@dharmanshah1239 4 жыл бұрын
I have a doubt..Many articles suggest that destructors delete the object.So does destructor actually deletes the object or just called when the object is about to destroy??
@serkanozturk4217
@serkanozturk4217 2 жыл бұрын
Personal notes: - Destructor is called whether the instance is in stack or heap
@gtorres94
@gtorres94 Жыл бұрын
Why is the destructor called twice? I understand that it's automatically called once you leave the scope of "Function". But if you call it manually from within "Function", like the last example, how is it possible that you can destroy the same object twice?
@syedsamarabbas5349
@syedsamarabbas5349 4 жыл бұрын
Good content and explaination! Could you please tell that when an object is passed by value to a function why destructor is called??
@ISKLEMMI
@ISKLEMMI 4 жыл бұрын
@Peterolen This is definitely an easy mistake to make in C++ if you're accustomed to using a language like C#, where the default behaviour is to pass a copy of the instance's memory address to the function/method.
@王裕萍-f3l
@王裕萍-f3l 7 ай бұрын
Thanks for your video! It's amazing! However, I would like to know the meaning of "we will only see the destructor being called when the main function exits which we wouldn't really see". Because I write a program: #include using namespace std; class B{ public: B(){cout
@ToyReviewsAndUnboxing
@ToyReviewsAndUnboxing 4 жыл бұрын
Hey Cherno, just curious...why don't you use the namespace for std cout?
@thanostitan.infinity
@thanostitan.infinity 4 жыл бұрын
he made a video for that, you can check that out :)
@deepthiumak
@deepthiumak 2 жыл бұрын
when the process/exe killed, will the destructor be called?
@asifkhan-mr8nj
@asifkhan-mr8nj Жыл бұрын
Very informative great
@RogerTannous
@RogerTannous 4 жыл бұрын
I'm doing the tests on a Linux (Debian) machine, and I can see (as I expected) the "Destroyed Entity" message(s) on the console because I'm manually running the command. As you're trying it with Visual Studio (or any such IDE), it would be impossible to see it. In order to make more experimentations, I've kept the non-default constructor (which takes float x, float y) and I've added std::cout
@darkengine5931
@darkengine5931 4 жыл бұрын
I hope you don't mind me asking, but has no one taught you to use the debugger yet to trace the side effects of one line of code at a time? I would prioritize learning that immediately if not. It can rapidly accelerate your understanding of program behavior stepping through one line of code at a time and seeing what each individual line of code does. It's crazy to me how many unis have third-year CS students who still don't know how to use a debugger. Their professors are crazy.
@RogerTannous
@RogerTannous 4 жыл бұрын
@@darkengine5931 So, you assumed I'm a fresh graduate CS student ? For my embedded systems stuff, I use the debugger often (with ARM Keil uVision for example), it's quite useful, sometimes it's even crucial. But now I'm short on SSD disk space on Windows, so I didn't install the required stuff for Visual Studio to be able to do C++ development. So the reason behind this is completely different than you thought, don't make fast judgments. Furthermore, even if I had VS and could use the debugger, as I'm following this interesting series on C++ to refresh my memory, I will also do the same on Linux (Debian), at least for curiosity (remember, some stuff are OS and compiler dependent!). As a side note, I rarely use desktop environments with Linux (any distro), due to the nature of my work (I'm an M.E. in Systems and Networking, with a former BS in Telecommunications). So I SSH to one of my test servers and do my testing. Is there still any problem here ?
@darkengine5931
@darkengine5931 4 жыл бұрын
@@RogerTannous Cheers. Apologies for my mistake. I thought it was one of those cases where people were sprinkling a lot of code to get input to simulate a debug breakpoint instead of GDB or firing up the MSVC debugger. It's alarmingly common in my experience that CS professors will teach two or more years of CS while their students are still oblivious to the debugger when I think they could be learning twice as fast with one in hand.
@RogerTannous
@RogerTannous 4 жыл бұрын
@@darkengine5931 it's ok :)
@tianyuez
@tianyuez 6 жыл бұрын
Genius
@kolohai
@kolohai 6 жыл бұрын
#include int main() { std::cout
@MrNucleosome
@MrNucleosome 5 жыл бұрын
SEGMENTATION FAULT
@danilobrandolin4287
@danilobrandolin4287 5 жыл бұрын
#include #define LOG(x) std::cout
@computerprogrammer7942
@computerprogrammer7942 3 жыл бұрын
What’s the point of returning 0 anymore do people still use it lol
@aabhash.01
@aabhash.01 Жыл бұрын
awesome
@pamp3657
@pamp3657 Жыл бұрын
good video
@footballCartoon91
@footballCartoon91 2 жыл бұрын
ok now i understand that deconstructor is called automatically when the program is calling the constructor
@highconsciousness240
@highconsciousness240 6 жыл бұрын
best website for c++ practice problems/ C++ resources?
@chimpionboy
@chimpionboy 6 жыл бұрын
Nice.
@lxy1312
@lxy1312 5 жыл бұрын
outro song plox
@bloodwolf8307
@bloodwolf8307 4 жыл бұрын
good
@int-64
@int-64 4 жыл бұрын
what's stack heap memory
@KshitijKale
@KshitijKale 4 жыл бұрын
He talks about it in video number 54.
@abdullahsaid181
@abdullahsaid181 11 ай бұрын
Y R U G
@chrisvidal1683
@chrisvidal1683 6 жыл бұрын
So is a destructor necessary? I'm asking based on the fact that when he called it manually it showed the destructor twice. Or is it used when you need to keep the code running but delete the class? Ex: Class PriceofProduct {run methods] delete for next transaction, etc.
@isaiasdimitri4110
@isaiasdimitri4110 4 жыл бұрын
Goodbye FISHIIIIUUUU
@ButerWarrior44
@ButerWarrior44 3 жыл бұрын
still dk when to use destructor
@bringiton2100
@bringiton2100 4 жыл бұрын
im not homosexual but you are a so so great programer !! hahaha
@bringiton2100
@bringiton2100 4 жыл бұрын
Hahahah i was kidding but this guys is just so fucking great I can't believe it. I have been looking for many years some one that could explain this concepts at low level. Probably you don't believe this but for 8 years i wasn't able to find any person who could explain these concepts. I'm very very very impressed.
@marflage
@marflage 5 жыл бұрын
Just as destructor is called automatically when the scope is finished and can be called manually as well, can the same happen with constructor?
@_slier
@_slier 4 жыл бұрын
smart pointer use destructor
@bl00zzard40
@bl00zzard40 4 жыл бұрын
So, Constructors and Destructors are not very commonly used in the programming world?
@gamingtance_3804
@gamingtance_3804 4 жыл бұрын
it pains me seeing "linus fake tech tips" getting 1000000+ views but your videos don't get that much!!!
@xrafter
@xrafter 4 жыл бұрын
@Artem Katerynych Hey you didn't i see you somewhere before?
@aakashmankara
@aakashmankara 6 жыл бұрын
video is super fast
@mask5344
@mask5344 Жыл бұрын
use using namespace std; nub
@spdjoker3
@spdjoker3 Жыл бұрын
Lmao you shouldn’t use using namespace when you work professionally. Its bad practice because it means anyone using your classes will have to also use those namespaces.
@gda702
@gda702 5 жыл бұрын
oh bloody EL std everywhere over here too. Its a tutorial, for us new programmers you shouldve used namespace std.
Inheritance in C++
8:00
The Cherno
Рет қаралды 400 М.
Object-Oriented Programming is Bad
44:35
Brian Will
Рет қаралды 2,3 МЛН
路飞做的坏事被拆穿了 #路飞#海贼王
00:41
路飞与唐舞桐
Рет қаралды 26 МЛН
Function Pointers in C++
12:41
The Cherno
Рет қаралды 397 М.
Copying and Copy Constructors in C++
20:52
The Cherno
Рет қаралды 439 М.
Every Programming Language Ever Explained in 15 Minutes
15:29
Flash Bytes
Рет қаралды 360 М.
Become a Malloc() Pro
6:58
thedoubleeguy
Рет қаралды 12 М.
Stack vs Heap Memory in C++
19:31
The Cherno
Рет қаралды 583 М.
The Ultimate Tier Programming Tier List | Prime Reacts
26:57
ThePrimeTime
Рет қаралды 500 М.
Virtual Destructors in C++
7:55
The Cherno
Рет қаралды 107 М.
are "smart pointers" actually smart?
9:44
Low Level
Рет қаралды 79 М.
C++ vs Rust: which is faster?
21:15
fasterthanlime
Рет қаралды 407 М.
POINTERS in C++
16:59
The Cherno
Рет қаралды 1 МЛН