Handmade Hero | new vs delete | struct vs class | How to get fired

แชร์
ฝัง
  • เผยแพร่เมื่อ 17 ธ.ค. 2024

ความคิดเห็น • 218

  • @Hyp3rborean
    @Hyp3rborean 5 ปีที่แล้ว +213

    1. Getting two munom
    2, Iwitiau tho pronency
    3. Denitiaun iwo no muncy
    4. Fruting ntu muncry

  • @MidnightSt
    @MidnightSt 3 ปีที่แล้ว +59

    i love rants by people much smarter and more knowledgeable than I am, it's one of the best learning resources.

  • @JCStelu
    @JCStelu 7 ปีที่แล้ว +142

    7:39 "But, suppose you were to introduce a virtual function. Heaven help you. First, you would get fired from my team. But then second what would happen is, inside this (foo) struct, the compiler would silently introduce a pointer to what's called a VTable, which is a dispatch table - that is how it actually implements virtual functions. Now, you have no way of initializing that virtual table yourself, because you don't even know where.... you don't know anything about that - that's a compiler detail. And so one of the things "new" also does, is it initializes any hidden information that you did not put there, but the compiler did. And so, if you start using compiler features, C++ features, that the compiler needs to augment the structure of the class with, and which have important inititialization that has to happen, you must call "new", even if you don't care about the compiler calling your constructor. Because the compiler, essentially, has a constructor that has to get called and it is initialization of that VTable."
    Thank you, Casey.

    • @myungkeon
      @myungkeon 4 ปีที่แล้ว +2

      Could you explain why it is a bad idea to use virtual functions? I'm pretty new to cpp

    • @UnicycleBloke
      @UnicycleBloke 4 ปีที่แล้ว +30

      @@myungkeon It's not a bad idea. In some niche areas people are trying to maximise memory cache efficiency, virtual functions can be problematic because the (implicit) indirection through function pointers reduces the likelihood of a cache hit. This is definitely not something for beginners to worry about. In general they are absolutely fine. Based on what I've seen, this guy prefers C and only knows enough about C++ to complain about things he doesn't like. What a stupid video!

    • @berksteraydo9517
      @berksteraydo9517 3 ปีที่แล้ว +26

      @@UnicycleBloke knows enough c++ to complain about things he doesn't like? are you a joke? you don't know the guy and probably never did as big of a project as his smallest product...

    • @UnicycleBloke
      @UnicycleBloke 3 ปีที่แล้ว +12

      @@berksteraydo9517 kind of late to the party, aren't you? FWIW I have been writing C++ for 30 years, in projects large and small, in a number of domains from Windows GUI to hard real time embedded. My recollection is that the video was just nonsense.

    • @berksteraydo9517
      @berksteraydo9517 3 ปีที่แล้ว +2

      @@UnicycleBloke yeah it was taken in 2015 so I am a little late. I respect your time spent on those projects, and if you say it's nonsense then it is. Btw c++ is 35 years old and maybe it deserves some critical approach. just maybe.

  • @AddyGoesPlaces
    @AddyGoesPlaces 4 ปีที่แล้ว +106

    This guy just wants to program in C.

    • @higgins007
      @higgins007 4 ปีที่แล้ว +51

      C with function and operator overloading.

    • @RockTo11
      @RockTo11 3 ปีที่แล้ว +61

      Don't we all?

    • @isodoublet
      @isodoublet ปีที่แล้ว

      @@RockTo11 Only insane blowhards.

    • @guckesksk5895
      @guckesksk5895 ปีที่แล้ว +3

      @@higgins007C structs with “self” method and in-struct initialization would be the best C

    • @sdwone
      @sdwone 11 หลายเดือนก่อน +4

      As the man said... Program in a language that YOU want to use! Just because he doesn't like C++ DOESN'T mean that YOU must hate it too!
      Ergo... There is NO such thing as the PERFECT language! Context and personal preferences matter! So all this dogging against devs who don't like YOUR language of choice is ultimately pointless!!!
      End Of! And you go and find your OWN way in Coding Life!!! And if you cannot find your own way, then you have no choice but to DO some homework, and way up the pros... And the cons... That other devs opinionate over!
      I.e. YES... As a developer you are on your own! There is no Borg Collective!
      Deal with it!!!

  • @ChrisAthanas
    @ChrisAthanas 2 ปีที่แล้ว +32

    I always thought a class was just a struct and C++ programmers would argue with me about it. Thanks for vindicating my position

    • @biskitpagla
      @biskitpagla 2 ปีที่แล้ว +6

      This is because most C++ programmers started with C or the subset of C++ that looks like C and stopped using structs when they learned about OOP.

    • @babgab
      @babgab ปีที่แล้ว +9

      It effectively is. The only difference between struct and class in C++ is that structs' default visibility is public while classes are private.

    • @ChrisAthanas
      @ChrisAthanas ปีที่แล้ว +2

      @@babgab Now I'm learning swift and they are calling classes 'struct' in the language lol

    • @Mallchad
      @Mallchad ปีที่แล้ว

      Like somebody said classes and structs in C++ are identical with strcuts being public by default.
      in C structs are very limited and can only take variable definitions and nothing else. except maybe with designated aggregate initialization (named initialiser list parameters)

    • @bertiesmith3021
      @bertiesmith3021 5 หลายเดือนก่อน +1

      Only if they don’t actually know c++. This is one of my interview questions if I suspect that the interviewee is actually a c or Java programmer pretending to know c++.

  • @esben181
    @esben181 5 ปีที่แล้ว +74

    I remember watching this some years ago when I was skeptical of C. Now I am skeptical of C++

    • @sdwone
      @sdwone 10 หลายเดือนก่อน

      C++ is a great language! I mean, lots of games, particularly high end games, are still written in C++! So yeah, that has to count for something!
      But that said, the language does have it's fair share of issues! Namely, it's a mix of different bits of other languages bolted together... And thus, mastering C++ takes time as you navigate which bit of the language is best to use in particular situations etc.
      As for the perceived weaknesses, such as garbage collection... Well yes, that can be a pain, but thanks to the Boost Library, there are plenty of well tested, high performant types that can handle all that for you anyway, in a way that is fully under your control. I.e. you get to dictate when memory gets automatically released by these types. As opposed to languages, like C# (another FINE language! All C type languages are!!!) in which garbage collection runs when it's ready. You can of course invoke this yourself, but may face performance penalties if the GC has to do a lot of cleaning up.
      So yeah, as with lots of other languages, C++ is continually evolving so... Don't count this language out just yet!!!

    • @SnakeEngine
      @SnakeEngine 4 หลายเดือนก่อน

      Now you should be skeptical of yourself.

    • @esben181
      @esben181 4 หลายเดือนก่อน +2

      @@SnakeEngine I've become a skeptic.

  • @dgmsstuff
    @dgmsstuff 9 ปีที่แล้ว +31

    you should indicate from what episode it was taken! :)

    • @vexedev
      @vexedev  9 ปีที่แล้ว +21

      +dgm's stuff day 157 poststream QA

  • @ishdx9374
    @ishdx9374 3 ปีที่แล้ว +3

    why does the title say "new vs delete"

  • @Glomly
    @Glomly 5 หลายเดือนก่อน

    So, an empty constructor new = malloc, and empty destructor delete = free?

    • @СергейГордиенко-п4д
      @СергейГордиенко-п4д 4 หลายเดือนก่อน

      Not exactly. One case I might think is a class/struct having field that are not primitive in that sense.

  • @timog7358
    @timog7358 5 หลายเดือนก่อน

    nice

  • @maxim25o2
    @maxim25o2 4 ปีที่แล้ว

    5:26 You mean that correct using in c++ is struct? because class is something overshoot idea? And i can totally ignore learning class how to use, and focuse only at struct?

    • @SC1240
      @SC1240 4 ปีที่แล้ว +3

      the only difference between struct and class is default data access. Class defaults to private data accessors, while struct defaults to public. You could change either though to change the access to whatever you want for the data within it. If you know how to use class, struct is the exact same. You still need to know how they work though and what a struct is and how it's represented in memory.

    • @DanielKierkegaardAndersen
      @DanielKierkegaardAndersen 3 ปีที่แล้ว +2

      Note that this is the case for those two languages, and that managed languages like C# and Java, have bigger differences between Structs and classes.. As Structs are value types in those languages ;)

  • @majoro7251
    @majoro7251 9 ปีที่แล้ว +1

    This is awesome! Reminds me of the need to continue reading my reversing book xD

  • @mariostelzner4530
    @mariostelzner4530 2 ปีที่แล้ว +10

    6 YEARS AGO! I THOUGHT IT'S ONLY BEEN NO MORE THAN 4. I WONDER IF HE'LL EVER FINISH THIS COMPUTER GAME.

    • @Theonewhowantsaname
      @Theonewhowantsaname ปีที่แล้ว +14

      For your information (and anyone else stumbling over this comment), the total time of the playlist of all Handmade Hero videos, according to a playlist length calculator plugin in Chrome, is currently approximately 1312 hours. If we assume 40 hours of work per week that would be a bit less than 33 weeks, i.e. about 8 months of full time work.
      I haven’t followed the whole series, so I don’t know if Casey did significant work off stream. If someone knows they can correct me, but if most of the work is recorded and available in his videos, this game has taken about 8 months full time for one experienced developer to make. I know it’s not a fully complete game but I believe Casey has said it is mostly finished, and the parts left are more game design related which is not his expertise. I don’t think that’s an especially long development time at all.

    • @TheSandvichTrials
      @TheSandvichTrials ปีที่แล้ว +4

      @@TheonewhowantsanameCasey hasn’t done any work outside of the stream at all, actually

    • @zhulikkulik
      @zhulikkulik ปีที่แล้ว +2

      ​@@Theonewhowantsaname afaik he never worked on it offstream.
      Really the problem with hmh is that it got out of control very quickly. It's not a structured source of information but literally a collection of livestreams of a smart guy making an engine. Good luck finding something about a certain topic among those videos - no timecodes, no episode guide, no comments to at least let someone post timecodes for other viewers.

    • @castleofthewinds
      @castleofthewinds ปีที่แล้ว

      He would have probably finished it by now if he had used new, delete, classes, inheritance, polymorphism, and templates. Basically, if he had written it in proper C++ rather than messy C.

    • @etodemerzel2627
      @etodemerzel2627 10 หลายเดือนก่อน +3

      @@zhulikkulik FYI: Every episode is transcribed. You can use a search on the official site using any keyword or a phrase to find out if and where the desired topic is covered.

  • @broken_abi6973
    @broken_abi6973 7 ปีที่แล้ว +9

    Apologies if I misunderstood your point. But are you actually against the culture of destructors being called implicitly by default? Imagine if I have a struct with raw pointers inside. Are you suggesting that whenever I create one of this structures, I have to look for the end of the scope where it gets destroyed, and explicitly call a function destroy_...() to clear the internal ptrs? If so, that seems total nonsense to me.

    • @rationalcoder
      @rationalcoder 7 ปีที่แล้ว +26

      Well, first, he would probably say that the idea that you would be stuck in a super dynamically allocated RAII situation like that is avoidable by having a better understanding of the lifetime of your data. That being said, I doubt he is against deterministic destruction, as even Jonathon Blow has this in Jai, with defer.

    • @jeeperscreeperson8480
      @jeeperscreeperson8480 2 ปีที่แล้ว +2

      What kind of chaos are you programming?

    • @broken_abi6973
      @broken_abi6973 2 ปีที่แล้ว +3

      @@jeeperscreeperson8480 no chaos. This is a basic concept in c++ and a more maintainable one than defer

    • @broken_abi6973
      @broken_abi6973 2 ปีที่แล้ว +1

      @@rationalcoder after several years of programming, I have to say that this "super dynamically allocated RAII" situation that is hard to comprehend basically never materializes. From my experience, RAII scares C programmers at first, they tend to resist it, but once they accept it and start reading code with RAII in mind, they admit their fears were misplaced. For me, code with defers seems harder to maintain.

    • @rationalcoder
      @rationalcoder 2 ปีที่แล้ว +4

      @@broken_abi6973 That's what people are betting on, of course. It can't materialize because if and when it does, the project can easily be unrecoverable. That's (part of) what happened at my company. If you can get away with just using tested code that other people have written and/or just use the standard library, as long as that's good enough, hopefully you can squint your eyes and just move on to another project. We are currently in the process of a complete project rewrite, and ultimately, _multiple_ complete project rewrites. Admittedly, we've had much greater problems than RAII, but I digress.
      Once you have enough people writing RAII wrappers on top of RAII wrappers, bugs slip through and they become a nightmare to debug b/c the problem is in some implicit object-lifetime code that's calling some other object-lifetime code etc.
      To be clear, I'm not saying I wouldn't like the option to have the compiler generate defer calls to "destructors" of members, C++-style if I want, but if I had to start with what C++ has vs type-safe macros and defer, I would choose the latter. That's especially true if it has a cultural effect resulting in memory not being thought of as some generic resource. People who don't rely on RAII tend to know how to remove complexity by allocating memory out of scopes and freeing the scope instead of having destructors try to free individual allocations by pointer. If you don't need to free memory, most destructors don't need to exist.

  • @minma02262
    @minma02262 5 หลายเดือนก่อน

    Does handmade hero have any timestamps on their video. This sort of resources are very valuable for newcomers. But expecting people to watch 8 years of video to watch what they need is a bit unpractical

    • @vexedev
      @vexedev  5 หลายเดือนก่อน +3

      Yep they do. handmadehero.org/ Scroll to the bottom here, use the query text field to search for keywords, the videos have timestamps with tags generated by the community and that's what it uses to search.
      You could treat it as a reference so watch/learn about things you're interested in and move on. If you have the time, watch maybe the first 50 eps or so, watching him solve problems, how he thinks and approaches things is invaluable, no book or other tutorial will teach you that. The stuff about hot reloading is a game changer also.
      If you want more condensed focused info, you could check out his performance oriented course, I've only seen clips never paid for it but its Casey so its gonna be really quality content.

    • @minma02262
      @minma02262 5 หลายเดือนก่อน

      @@vexedev Thank you for the resource. Is his course completed or still creating?

    • @vexedev
      @vexedev  5 หลายเดือนก่อน +1

      @@minma02262 I'm not really sure as I haven't taken it, but its a lot more structured and 'lecture'y like than HMH www.computerenhance.com/p/table-of-contents

    • @minma02262
      @minma02262 5 หลายเดือนก่อน

      @@vexedev thank you

  • @berksteraydo9517
    @berksteraydo9517 3 ปีที่แล้ว +12

    people in the comments:
    for(;;){
    t* a = new t[100];
    delete[] t;
    }
    and t:
    class t : private tparent{
    set
    get
    set
    get
    set
    get
    set
    get...
    }

    • @vexedev
      @vexedev  3 ปีที่แล้ว +4

      LOL

  • @UnicycleBloke
    @UnicycleBloke 4 ปีที่แล้ว +27

    operator new does not initialise the v-table. The constructor does this. In fact the compiler creates the v-table and all the constructor really does is place its address in a pointer member of the struct or class. The constructor also does this when you create an object on the stack or as a global (in this case the constructor is called by the runtime before main()). Calling new Thing allocates memory for the object with operator new, and then calls the Thing constructor. The reason that constructors are always called in this way is to help ensure correct initialisation. An unitiliased object is a bug waiting to happen. You write your constructor to initialise the object. When the constructor returns, the object is safe to use, so long as your constructor does its job properly. Why would anyone in their right mind think this is a bad idea?
    Calling the destructor when an object goes out of scope or is deleted allows us to easily implement efficient deterministic automatic garbage collection, even in the presence of exceptions (RAII). Destructors are arguably the most important and useful feature of the entire language, and this fellow dismisses them out of hand. I haven't leaked resources at all in many years.

    • @OMGclueless
      @OMGclueless 2 ปีที่แล้ว +14

      This is being overly pedantic. Operator new initializes the v-table, because operator new calls the constructor, which initializes the v-table. In fact, "calling the constructor" is even more fundamental to operator new than allocating memory is: you can use operator new without allocating at all by passing a memory location as an extra argument in parentheses to operator new. If you do this it *only* calls the constructor (this is called "placement new").

    • @isodoublet
      @isodoublet ปีที่แล้ว +4

      @@OMGclueless "This is being overly pedantic. "
      No, it's not. The entire point is that the language bakes in, by design, the idea that objects are valid from the end of the constructor to the beginning of the destructor. That's why it's done, and that's why new calls the constructor. It allows the coupling of lifetime to lexical scope which has been extremely fruitful as the OP stated.

    • @marcossidoruk8033
      @marcossidoruk8033 ปีที่แล้ว +12

      ​@@isodoublet Yes it absolutely is, as the other guy explained operator new is just a way of calling the constructor, so saying "new does not initialize the V table the constructor does" is absolutely overly pedantic.

    • @isodoublet
      @isodoublet ปีที่แล้ว +2

      @@marcossidoruk8033 Calling people pedantic is just a way of saying "you're right, I'm wrong, but it DOESN'T MATTER." Please do better.

    • @marcossidoruk8033
      @marcossidoruk8033 ปีที่แล้ว +7

      @@isodoublet He didn't just call him pedantic, he elaborated as to why he is pedantic, you misrepresenting the meaning of the word pendantic in order to ignore his whole line of argumentation is not a very smart response, do better.
      And no, calling someone pedantic doesn't mean "you are right, I am wrong, but it doesn't matter", pedantic means (according to the Cambridge online dictionary) "giving too much attention to formal rules or small details" or "caring too much about unimportant rules or details and not enough about understanding or appreciating a subject", you may want to check your English.
      And yes, I am being pedantic now, but since according to you (rightfully) accusing someone of being pedantic is somehow self defeating I guess you can't do anything about it, can you?

  • @roadent217
    @roadent217 5 ปีที่แล้ว +4

    So, besides the "new" and "delete" keywords being seemingly superfluous additions to the c++ language (like "print" is in Python 2), is there any reason to loath that fact alone? Casey makes a case (pfft...) that he'd rather just have a function that allocates and initializes the memory (like "print()" in Python 3). But, like, what's the difference?

    • @yogxoth1959
      @yogxoth1959 4 ปีที่แล้ว +22

      Don't take that stuff too seriously. Some people treat programming and programming languages like it's a religious war.

    • @9SMTM6
      @9SMTM6 3 ปีที่แล้ว +3

      The thing is they are intransparent, and I do agree with him on that.
      If you explain to someone what all goes into making these work for some classes it's a mess.
      I mean try and explain a move constructor to someone that just uses C++ for generic things.
      As another Rust fanboy these days I think Rust does it quite well with Box for Heap allocations, no specific concept for initialization - but a convention for an associated function ("static method" in C++) called new - (as you might want to initialize in many different ways) and drop for deinitialization.
      Rust does a really great job of making many extra concepts in C++ much more transparent, and easier to use while mostly keeping the same capabilities.
      Static methods? Just methods that don't take self (aka this) as paremeter (like python does it).
      Move-Constructor etc? Move is the default without any specific code needed, and switching to the way C++ handles it is easy, unless it would be a bad idea anyways.
      Virtual functions/vtables/type-erasure? Don't need to be specific functions in Rust and are still more explicit. Instead of a declaration on function level theyre a thing only when you have references with a given trait (interface), in that case all functions of that trait are virtual, otherwise you can call them statically without the overhead.
      New/delete? Just a wrapper called Box that ensures free with RAII. The latter is a thing in C++ too.
      Inheritance, Classes? Not a thing. There's just Interfaces (traits, have some capability of automatic implementation to supplant traditional inheritance) and structs. Name conflict of methods from different traits? Not a thing. A method is identified not only by name but by name and it's trait (this sounds like pain, but in most cases the name suffices, even if you implemented two interfaces that both have a function of the same name. I'll skip the explanation).

    • @bertiesmith3021
      @bertiesmith3021 5 หลายเดือนก่อน

      They are not superfluous. They do things that Casey wants to do himself. Most of us are not clever enough or dedicated enough to get it right, so we get the compiler to generate that code for us.

  • @ishdx9374
    @ishdx9374 3 ปีที่แล้ว +3

    can someone give me a timestamp for getting fired ? thx

    • @ZantierTasa
      @ZantierTasa 3 ปีที่แล้ว +2

      7:47

    • @eugenkeller
      @eugenkeller 4 หลายเดือนก่อน

      You can get fired at any timestamp, like now().

  • @realdomdom
    @realdomdom 2 ปีที่แล้ว +13

    I can see why he disabled the comments under his videos.

  • @TechnologyRules
    @TechnologyRules 5 ปีที่แล้ว +9

    Why this guy disable comments on his videos? In his Twitter account he says "Account is post-only, replies and DMs aren't read." What is it, some kind of social pathology? I like watching him programming, though.

    • @vexedev
      @vexedev  5 ปีที่แล้ว +19

      I've been there from the very beginning, dont think he's ever enabled comments. It's similar to Per Vognsen doing Bitwise, guys just want to share information, comment sections get inflamed sometimes, they're not interested in that I guess.

    • @krinjon193
      @krinjon193 4 ปีที่แล้ว +6

      Can anybody explain why this guy would fire me for introducing virtual function . Or is this his style of talking.

    • @DB-pt6zj
      @DB-pt6zj 4 ปีที่แล้ว +14

      He has better things to do than try to micro manage the toxicity that is comment sections.

    • @Borgilian
      @Borgilian 4 ปีที่แล้ว +26

      Well, when you are a guy like Casey, who's programmed engines (among other critical pieces of software) for more than 30 years, worked(or still works) at RAD Game Tools (a company that revolutionized animation technology and powers data compression in the upcoming PS5 with Oogle Kraken) and has pretty much seen almost all graphics programming designs, it becomes hard to interact with the "new crowd". Not from a lack of communication and open debate, mind you. Mostly from the new crowd's lack of knowledge & being subjected to corporate programming brainwashing.
      Almost all of his twitter posts had comments from (mostly) web developers who felt like he was personally attacking their favorite OOP paradigm and didn't understand what he was trying to explain. Most of them don't really understand how their CPU works, yet they call themselves programmers, and believe that anybody who's straying from the mainstream One True Way TM (OOP + Design Patterns) is a heathen.

    • @vborovikov
      @vborovikov 2 ปีที่แล้ว +2

      @@Borgilian videogame programming represents a tiny fraction of practices in the industry but these guys are very eager to teach us doing things the right way

  • @majoro7251
    @majoro7251 9 ปีที่แล้ว +19

    "First of all, if you're using virtual functions you're from my team" xD

    • @cutelittleball
      @cutelittleball 9 ปีที่แล้ว +15

      +Major O way to misquote ;)

    • @majoro7251
      @majoro7251 9 ปีที่แล้ว

      +cutelittleball oops missed "not." xD

    • @etodemerzel2627
      @etodemerzel2627 7 ปีที่แล้ว +24

      +Major O He said "first, you would get fired from my team".

  • @krinjon193
    @krinjon193 4 ปีที่แล้ว +5

    Can anybody explain why this guy would fire me for introducing virtual function . Or is this his style of talking.

    • @roadent217
      @roadent217 4 ปีที่แล้ว +16

      I'm guessing it's because creating a virtual class introduced a "silent" (hidden) pointer to a vTable, that the compiler knows about, but the programmer doesn't? And that calling a virtual function has the program consult the pointer to get to the vTable to find where the virtual function's code is located, which may, in some cases, have a considerable performance impact on your application? Not to mention that the function calling syntax doesn't differentiate between a regular function and a virtual one. And also that trying to manually initialize your class inside a malloc'd memory space is a big no-no, and will crash your program, because the programmer isn't able to personally set the vPointer necessary to find the virtual function. For a guy working on video games so close to the hardware, I bet he just has a pet peeve about third-party programs (i.e. compilers) rearranging the code under the hood, where a boost in speed for calling a function measurable by microseconds can have a significant impact on the speed of your program. This advice may not apply for a web app (or other types of) developer.

    • @wiktorwektor123
      @wiktorwektor123 3 ปีที่แล้ว +7

      He's talking in very specific context, game and game engines developement that are very time critical applications. If you introduce virual function and use multiple inherited types from class, you adding every time pointer to VTable, that is only known at runtime. More inherited types you have the bigger the table. Now if you calling that function thousnds times per frame or millions you pay cost of serching that table and jumping to function adress in memory. By making function virtual you telling compiler that this function cannot be inlined, because compiler cannot know which one, call during compilation. And if this function is your bottleneck in code during profiling you have absolutely no way to optimize it, or tell compiler: do not call it, just every time you see this, inline it's body.

  • @nativesun7661
    @nativesun7661 4 ปีที่แล้ว +2

    Great stuff!

  • @dabunnisher29
    @dabunnisher29 3 หลายเดือนก่อน

    WHY ARE YOU STEALING FROM HANDMADE HERO?

  • @maxim25o2
    @maxim25o2 4 ปีที่แล้ว +1

    10:04 I am learning c++ and almost everybody try to teach on TH-cam that constructor and destructor are manual menaging memory of constructing things. It means that when I am not able to call function or class at in side of main, but in side of a third hierarchy function, and that class or struct I want have to live ass long ass possible out side of function to be able to use it a cross of my program, that was not the purpouse of constructor and destructor??
    By the way, NEW and DELETE I think that this was borrowed from c# where they are using it notoriously, almost for everything, where c and c++ have different way of thinking about objects. And c++ merge that idea for peoples from c# that they could write library more compatibility for cross platform.

    • @xpilarz0
      @xpilarz0 4 ปีที่แล้ว +4

      just go to the wiki and read when c++ and c# were introduced and what functions they had

    • @ferociousjuggler2668
      @ferociousjuggler2668 4 ปีที่แล้ว +3

      @@xpilarz0 i feel like this person is trolling

  • @evan_game_dev
    @evan_game_dev 2 ปีที่แล้ว +2

    new and delete should have just been malloc and free except it automatically gets the size for you

    • @boptillyouflop
      @boptillyouflop ปีที่แล้ว +5

      Nah, new and delete have a very good purpose: they let containers like std::vector to know what to do on new items when growing the array, and what to do to removed items when shrinking (including doing new and delete on std::vectors contained in these items).
      Placement new and placement delete are fine. It's the memory allocations in malloc/free and new/delete that are the problem and generate an endless amount of bugs and are not necessary anymore. Dynamic memory allocation should be done by containers ONLY - you should always let std::unique_ptr and std::vector and std::string and std::map and std::shared_ptr deal with malloc/free.

  • @MarincaGheorghe
    @MarincaGheorghe 3 ปีที่แล้ว +10

    quite opinionated introduction to c++. I wouldn't recommend taking all comments literally. Why constructors are more useful that writing things directly: the deinit phase is called automatically at end of variable scope for example(destructor). That is very usefull and the semantics of initialization/deinitialization is useful as a concept.

    • @hatema
      @hatema 3 ปีที่แล้ว +6

      oh you should definitely watch Jon Blow

    • @9SMTM6
      @9SMTM6 3 ปีที่แล้ว

      Eh, this is also not quite it I think.
      For once you are answering a question he didn't answer, and just like him you're combining two concepts in a strictly correct, but still misleading way.
      And you're making an outright mistake when saying when an object is deinitialized.
      There's constructors and destructors. These get called when the class is created (in that case it's provided with some memory) or when it's destroyed.
      There's 2 common ways to calla constructor in C++. With with new or without it. If you call it with new, the memory that's provided will be in the heap. If you call it without it'll be on the stack.
      The way you destroy an object depends on where it was created.
      If it was created on the stack, you don't have to care about deinitialization. It will happen when it needs to happen. Which is, btw, NOT always at the end of the scope, as the class can also MOVE (eg. if you pass it to a function that takes the class as value), in which case more complicated stuff can happen, but the easiest way to think of it is that the new value needs to and does do the cleanup.
      If the value is on the stack then you need to (or at least should) free the memory with delete, which will also before that call the destructor for deinitialization.
      In "modern" C++ there exist many classes that have hidden heap allocations and manage these with additional classes on the stack. For example std::vector, unique_prt, shared_reference etc.
      These are a neat way to use this RAII concept you refer to (which I'm a REALLY big fan of) also for memory management.
      Also, just a warning, while I'm fairly confident in what I've said here, I was never THAT experienced in C++, I privately mostly use Rust these days, and most of the knowledge I've said here is from conferences etc I've watched, as Rust and C++ are somewhat closely related in terms of memory model and also resource management (Rust offers more compiler support/warnings but ultimately works similar).

    • @OMGclueless
      @OMGclueless 2 ปีที่แล้ว +5

      @@9SMTM6 This is not accurate. The lifetime of an object on the stack always ends when control leaves the current scope, for example by execution falling off the end or a return statement or an exception being thrown. Even if you move from an object, the original object is still alive, and if it has a destructor that destructor will be called.
      What you're describing by saying an object is deinitialized-by-moving is called "destructive move". C++ does not have this. There have been several proposals to try and add it, and Rust has it, but C++ does not currently have it and there is no way to stop the destructor from being called. When you write an object with a move constructor and/or move-assignment operator, it still needs to be safe to call the destructor on a "moved-from" object and the compiler does always call it.

    • @9SMTM6
      @9SMTM6 2 ปีที่แล้ว +2

      @@OMGclueless jup, I've since seen that, thanks for the correction. You very correctly attributed it to Rust :).
      It is a shame, at least IMO destructive move does make a LOT more sense, the need for a moved-out state makes C++ RAII objects both harder to code and harder to use, as eg these smart pointers on purpose may contain nullptr etc.

    • @9SMTM6
      @9SMTM6 2 ปีที่แล้ว +2

      @@OMGclueless but, the main point should still stand AFAIK: If you initialized a C++ RAII class with "new" or similar, then you will have to explicitly call delete, which will call the destructor, that won't happen automatically. Just variables on the stack, OR if you use a smart pointer that lives on the stack to manage that resource class, the destructor call will happen automatically.

  • @theb1rd
    @theb1rd 8 ปีที่แล้ว +9

    one benefit of ctors and dtors and RAII is that after a while the compiler is writing all your ctors and dtors for you, correctly, and maintaining them for free

    • @burakcopur3841
      @burakcopur3841 7 ปีที่แล้ว +8

      I love C/C++ both but I believe C++ manages lifetime of your objects (objects in the sense of a typed portion of memory, not OOP) superbly. Any C programmer arguing against this is just fighting a hopeless fight. Sure you may need to work with memory directly, but custom allocators, new and free are always a better solution.

    • @123hgf456
      @123hgf456 6 ปีที่แล้ว +6

      How is this "free"?

    • @majormalfunction0071
      @majormalfunction0071 5 ปีที่แล้ว +1

      Burak Çopur without being able to iterate over class members, ctors/dtors can never be "free." Personally, I write C in hobby projects because of language simplicity. Personal preferences, horses for courses, etc. but I value doing the simplest thing that works. RAII only works if objects are on the stack. Reference counting with the reference as part of the object is the way to go IMO. Manual memory management in multithreaded apps is a no-go, so I'll meet you half way :).

    • @boptillyouflop
      @boptillyouflop ปีที่แล้ว +3

      @@majormalfunction0071 RAII does a great job on objects within other objects, especially containers like std::vector and std::unique_ptr... I haven't written a malloc/free/new/delete in *years* thanks to this.

  • @Euquila
    @Euquila 2 ปีที่แล้ว +5

    C fluff fluff

    • @boptillyouflop
      @boptillyouflop ปีที่แล้ว +1

      C++
      The first + is actually shipping large projects on time without unusable stuff like command line interfaces (otherwise you'd use plain C)
      The second + is that it doesn't become weirdly slow and stuttery once you have 10+ megs of data (otherwise you'd use C# or Java)

    • @eugenkeller
      @eugenkeller 4 หลายเดือนก่อน

      C fluff fluff ... no idea what it means but I like the term :D

  • @Fakheet
    @Fakheet 6 ปีที่แล้ว +31

    that's one hell of an illegible handwriting

    • @mikemcculley
      @mikemcculley 2 ปีที่แล้ว +3

      Not really. I think 4) FRUTING NTS MONORY is fairly legible.

  • @seditt5146
    @seditt5146 5 ปีที่แล้ว +12

    Weird, he proceeds saying new/delete is a terrible terrible idea but first stating a Terrible terrible idea of his own. Why the fuck write Alloc_init on your own just to mimic New,,, It makes no sense. I am starting to see why he has comments off on all his videos because I have seen him make many statements that are just off and kind of stupid to be totally honest. Then I have seen code of his that was so convoluted and messed up it is not even funny. Hmmm, idk really what to think about this dude sometimes.

    • @Borgilian
      @Borgilian 3 ปีที่แล้ว +2

      Jesus, you CPP redditors are absolutely shameless. You keep bashing the guy, making up decades of years of experience (or work in AAA studios) as if that makes you any smarter or is a justification for why Casey is wrong, and you never try to bring anything positive to the world or systematically prove him wrong with real world examples.
      Do you even have any idea how many decades of experience Casey has? Or how much time he's spent teaching people, FOR FKING FREE, advanced programming techniques? Do you even know in what circles and with what kind of people he interacts? Because I've been following him for a while, and he's involved in some heavy projects... He's basically pissing on you, and many other naysayers on reddit/twitter, from afar and with a strong stream. Ever heard of Bink? That's Casey. Ever heard of Granny 3D? Him again. Ever heard of RAD Game Tools compression tech? Casey's also involved. Do you even know how much engine architecture this guy has designed in his lifetime? You have absolutely no fking idea, and it shows. Ever heard of the big famous group of game developers who wrote Microsoft the letter about OpenGL, talking about how garbage the company is and how they're purposely keeping OpenGL down? Casey was one of the names on that list. He's pushing a goldmine of a channel for free, holds conventions that are dirt cheap in comparison with SIGGRAPH, all of this on top of teaching programming and working on other contract jobs.
      But you people? What have you ever done? I'll tell you what. You write half assed comments, don't even try to write a simple program to test his claims, completely dismiss his experience (while you barely have any... and no buddy, sitting on your ass for 25-30 years in a field doesn't automatically make you a good programmer) and then act all superior.
      www.reddit.com/r/cpp_questions/comments/jj215o/why_should_i_never_use_virtual_functions_casey/
      Wtf is this shit? 79 comments from people with hardly anything to back up their claims. Guess you people got butthurt after he stopped using Twitter because you can't vent your corporate programming brainwashing.

    • @seditt5146
      @seditt5146 3 ปีที่แล้ว +3

      @@Borgilian HA!, Literally I have NEVER used Reddit nor Twitter so Swing and a Miss... I am also well aware of who Casey is so again, Swing and a miss. Batting zero so far kid.
      Why do I have nothing positive to say? Idk, maybe because I was asking a question about something I obviously felt was stupid he was saying and doing...
      But thank you for proving my point and showing I was not the only one that seen the absurdity in those statements so like it or not you can discredit me, that's fine. Discrediting a mass of people all pointing out the same flaw in logic on the other hand is much harder( despite your weak effort to try).
      In this instance if I remember correctly my problem with his statements was he bitched about New and Delete only to go and write THE EXACT SAME SHIT NEW AND DELETE DOES! To me that is senseless to the max and simply makes your code shittier, harder to read, more prone to error and takes more time.
      Far as what I am seeing with the Virtualization, he semi gets a pass on that due to the age of the video but even then Virtual functions were BARELY a performance problem and largely just a made up one programmers bitched about that did not really exist. Now... almost all problems with them do not exist at all and even more they provide some compiler benefits for optimizations in newer C++ versions.
      But go on dude, if you like doing bullshit code, with bullshit work, for nonessential stuff and to make your code unreadable by others, unmanageable, prone to errors down the line all for absolutely little to no gain, by all means go for it but really, don't cry to me afterwards because I honestly don't give a shit about ya.

    • @seditt5146
      @seditt5146 3 ปีที่แล้ว +6

      @@Borgilian Funny part is, I personally like Casey and what he does. Think it is great what he is doing teaching people to code and spreading that knowledge around. I am sure he has helped many. But if you think I am going to let that stop me from what I personally see as flawed logic(seems others see it as well so its not just me) you are sadly mistaken. I was wondering why his comment section was turned off. I likely found it is all.

    • @BlazertronGames
      @BlazertronGames 3 ปีที่แล้ว +8

      ​@@Borgilian 90% of the criticisms I've seen against him are more about his arrogant attitude during these rants, rather than him being a bad programmer. Judging by the response to many of these rants, it seems like there's many genuine criticisms on things he's saying. Not claiming that he isn't skilled, or that what he's saying is false, but that he's exaggerating things or just assuming things e.g. something along the lines of "the visual studio dev steam are all terrible programmers", because it doesn't load as fast as it used to (despite many new things being added). Many criticisms I've seen against him are completely genuine. It seems like many things he says in these rants have truth to them, but are exaggerated, or he's made false assumptions about certain things etc. Non of this is discounting his skill as a programmer or acting superior. It's childish to have the attitude that someone can't be criticised, just because they're more experienced. No one's perfect.

  • @MrAbrazildo
    @MrAbrazildo ปีที่แล้ว +2

    5:18, actually, C++ got rid of C-struct, because it's dangerous. The all public mindset is a mistake to me. So, class is a meaningful word. And I personally like the idea of keeping struct as a different default. Plus, class can be used on template parameter, which is better than typename, to me.
    7:40, I agree. Virtual f() has an awful trade-off. It even justifies firing the guy. In Brazil, the employer needs to pay an extra charge if "the firing was unfair". So he could say: he used virtual f()s. Fair enough!
    9:02, wow, great idea: thousands of alloc_and_init_my_thing() unnecessary f()s being on the market, polluting it, just because companies don't want to use new/delete. The idea of these keyword is to keep the RAII principle.

    • @v-2schneider264
      @v-2schneider264 ปีที่แล้ว +2

      You are talking nonsense cause you seem to be another rookie coder.
      1. Your attempts to hide something in C++ are fun and silly. You can write thousands of private stuff but if I want to change something and I have a header file than all your privateness will be gone in a moment;
      2. You don't understand the idea behind alloc_and_init paradigm. If you think it will be thousand of them it means that you in your code already have thousands of "objects" with a lot of constructors. But Im sure that ~95% of those object are BS crap and needless complexity of OOP-minded person;
      3. RAII is a very bad idea and doesn't fit to C++ especcialy. If you weren't so rookie and think instead of listening to so called gurus of C++ you'd understand. But I'll give you a hint - destructors. C++ destructor is another mess of this "beautiful" language. What would you do if destruction of an "object" is failed? Destructors can't return values. You can't throw exception (you can but you know...good luck). Your RAII "object" will hang and you'll have a resource leak. So the whole idea of RAII is pure crap. But who cares these days, yes, rookie?

    • @empireempire3545
      @empireempire3545 ปีที่แล้ว +1

      "The all public mindset is a mistake to me." Please go back to the world of Java/JS/whatever other layer of hell you came from.

    • @bertiesmith3021
      @bertiesmith3021 5 หลายเดือนก่อน

      It would have been better to not create a new “class” keyword but instead make it mandatory to specify public or private. But that would have broken compatibility with C so that was never going to fly.

    • @MrAbrazildo
      @MrAbrazildo 5 หลายเดือนก่อน

      ​@@bertiesmith3021 I prefer the way it is. I don't like the code growing downward too much, so I can save 1 line, without messing things. Or maybe demanding to write: 'private struct', when it should use private by default.
      Anyway, in practice I've been using more the word 'struct', because I can omit the 'public:' line. I rather use the 'class' 1, but I use to define a type for key data in the class, and I also want it to be seen outside it. So in order to be defined before use and public at the same time, I need to start by the public content.

  • @bike4aday
    @bike4aday 3 ปีที่แล้ว +13

    He missed one key point. If you're using C++ class/struct it's because you want to enforce encapsulation which means you want to use private members. In C, all the members are public, so you have to say "hey dummy, don't touch this member or you'll screw it up". That's really the only benefit to classes is enforced encapsulation.
    They reason enforcing encapsulation may be helpful is because, although smart programmers know how to write safe code from scratch, they may not know how to use someone else's code safely. Thus making them unable to touch parts that shouldn't be touched makes it easier to share and use other people's code without the potential for tricky bugs to appear.
    This only became an issue when development teams became big with 200+ people and libraries were shared on the internet. Prior to this, which is the sort of environment Casey programs in, enforced encapsulation is like a sprinkle on a sundae, who cares haha.

    • @empireempire3545
      @empireempire3545 ปีที่แล้ว +2

      " If you're using C++ class/struct it's because you want to enforce encapsulation " No. Thats not the only reason why one might want to use structs - in fact this is a very bad reason.

    • @bertiesmith3021
      @bertiesmith3021 5 หลายเดือนก่อน

      @@empireempire3545so making the char*, capacity and length members of string private was wrong? Given the number of CVEs arising from c code handling of dynamic strings I would say that the facts disagree with you.

  • @wintermute701
    @wintermute701 4 ปีที่แล้ว +1

    There's also placement new which he didn't talk about at all.

  • @kallehed6330
    @kallehed6330 ปีที่แล้ว

    RAII be like

  • @damianwojakowski3006
    @damianwojakowski3006 8 ปีที่แล้ว +1

    Vexe, the new and delete keywords have a point. In most modern langauges there are constructors and destructors for classes. They are called when you create/destroy objects. C++ added this just to keep to the "standards".

    • @Borgilian
      @Borgilian 4 ปีที่แล้ว +13

      That's like saying: "In most countries there is a percentage of criminals on the streets. Therefore we should ensure the existence of a low percentage of criminals in our country, just to keep up with the standards".
      Just because popular features are copied into languages, it doesn't mean they are a good thing.

    • @isodoublet
      @isodoublet ปีที่แล้ว +1

      @@Borgilian Sure, except that the C++ object lifetime model is a huge success which makes most other languages look like they're stuck in the iron age. The C-like model advocated in the video is downright paleolithic by comparison.

    • @marcossidoruk8033
      @marcossidoruk8033 ปีที่แล้ว +1

      ​​@@isodoublet You wished.
      The C model presented here is almost the same if done correctly and there are plenty of modern languages with MUCH better features to ensure creation/destruction correctness like Rust.
      I don't know whats the big thing about C++ constructors/destructors, sure they make things slightly more comfy but thats it, no big thing at all, In C you can just write a create and a destroy function and the only difference will be that in C++ stack allocated objects are automatically destroyed when they go out of scope while in C you just have to write a destroy(object) at the end of the scope. c++ is slightly more comfortable but thats it, I understand if someone has a personal preference to do it the C way because it is almost the same.
      As for heap allocated objects? C++ does nothing to ensure correctness. Nothing. I don't get why people sell you this is somehow easier in C++, its literally the same as C, you keep track of the object lifetime and you call the destructor, modern C++ introduced smart pointers to ""solve"" this issue, but smart pointers introduce overhead and are basically a way to deal at runtime with something that should have been solved by static analysis, it is like fixing a spaceship with a piece of tape. Rust on the other hand actual does proper ownership static analysis, and though it is not a perfect language IMO if your deal-breaker is proper object lifetime management language support you should be using Rust all the way.

    • @bertiesmith3021
      @bertiesmith3021 5 หลายเดือนก่อน

      @@marcossidoruk8033what overhead does unique_ptr add?