std::move and the Move Assignment Operator in C++

Поделиться
HTML-код
  • Опубликовано: 26 сен 2024

Комментарии • 332

  • @MrSuperdude6
    @MrSuperdude6 4 года назад +153

    I really wish I had've just watched your entire C++ series instead of listening in any of my lectures. This has been miles more helpful and easy to understand than any programming class I've had.

  • @lucascoef
    @lucascoef Год назад +52

    I've just aced a C++ technical interview thanks to this video. Your ability to explain is unparalleled. Keep doing the good work!

    • @svenbtb
      @svenbtb Год назад +4

      i know this is 7 months old lol but congrats! Hope the job is going well and I hope to one day soon ace a C++ interview myself using what i learn from Cherno

  • @Dante3085
    @Dante3085 4 года назад +141

    A good ways to understand std::move() is that you are basically saying "I don't need the object that I am passing anymore. I am allowing someone to steal from it."

    • @supremedeity9003
      @supremedeity9003 4 года назад +15

      Voluntarily letting your stuff be stolen.

    • @glee21012
      @glee21012 4 года назад +11

      It basically steals the pointers, or takes ownership of them, very powerful, like Cherno says "no new allocation". I can only think of using it when I have a temp variable.

    • @Evan490BC
      @Evan490BC 3 года назад +8

      @@glee21012 The fundamental Computer Science concept here has to do with Type Theory, and in particular linear (more correctly, affine) types: any object can only be owned by a single owner at any given time. Because C++ is the way it is (i.e. a mess) it's harder to enforce. But it (i.e. C++) is a necessary evil.

    • @anon1963
      @anon1963 Год назад

      @@Evan490BC c++ is only a mess when your bad code makes it seem like a mess.

  • @boondocksripoff2237
    @boondocksripoff2237 4 года назад +276

    I now realize I still dont know the basics of c++

    • @1vader
      @1vader 4 года назад +45

      I thought the same thing after watching the video but honestly, it more so made me realize what a crazy and confusing language C++ is. Stuff like this is why I prefer C or Rust.

    • @jyl9063
      @jyl9063 4 года назад +27

      Move constructors/assignment is basic C++

    • @PixelThorn
      @PixelThorn 4 года назад +5

      @@1vader or C#, or Python...

    • @Dante3085
      @Dante3085 4 года назад +13

      @@1vader That's not even the difficult part of the story of move semantics. Research perfect forwarding and reference collapsing

    • @Stefan-tw3fo
      @Stefan-tw3fo 4 года назад +2

      @@1vader Same here.

  • @Drastonar
    @Drastonar 3 года назад +13

    This is something I did so many times in C, but my teachers never told me it was a concept (move). It's much clearer when to do what now and the class abstraction we can do in C++ helps the code to be cleaner.

    • @maysanghai123
      @maysanghai123 2 года назад +2

      I think what you must have been doing is a simple typecasting in school. This is just a specific version of typecasting which works specifically with rvalue references.

  • @ameynaik2743
    @ameynaik2743 2 года назад +38

    1. Instead of casting using
    (T &&)var you can use std::move(var)
    2. A good ways to understand std::move() is that you are basically saying "I don't need the object that I am passing anymore. I am allowing someone to steal from it."
    3. We need to always delete the current data before shallow copying the other data. Also we need to point other data to nullptr.

    • @malborboss
      @malborboss 6 месяцев назад +1

      4. Before moving the other object into ours we need to ensure that we are not moving the same object to itself. Otherwise data may be lost.

  • @brandoncfrey
    @brandoncfrey 4 года назад +11

    Not a clue what most of what you said means on a technical level. But still couldn't stop watching. Great video.
    C++ gods help me 😭

  • @RogerTannous
    @RogerTannous 2 года назад +3

    I like the sentence "steal everything from Apple" 🤣

  • @fabricedelannay7288
    @fabricedelannay7288 3 года назад +22

    14:05 distinction between constructor and assignement operator, that's why I rather prefer to use {} brackets with new object creation and use the = only for assignement operator :)
    (For instance : String name{"Cherno"};)
    By the way, huge and awesome work, thanks !

  • @thestarinthesky_
    @thestarinthesky_ 4 года назад +8

    The more I learn about C++, the more I realize that I know NOTHING about this complicated but amazing language! I could learn C++ for the rest of my life and still there would be much to know! 🤩😍❤️🥳

    • @__jan
      @__jan 4 года назад +1

      that's not a good thing

    • @thestarinthesky_
      @thestarinthesky_ 4 года назад +6

      @Prochy it is just the matter of preferences☺️ I would love to be challenged and C++ is a REAL programming language! C++ helps me to realize what is happening behind the hood, C++ gives insight into things I can’t see in other language! C++ is a miracle in the world of computer science! C++ being huge and big, makes you keep learning and learning! There will be always something new and challenging for you! That’s what I want! Never stop learning! 🙏❤️

    • @oracleoftroy
      @oracleoftroy 4 года назад +4

      @@__jan Some people like dead languages that never change, others like new features that improve their code clarity and performance. I'm of the opinion that C++ being an actively improved language is a very good thing, and having to continually learn new things is part of the job description of any software developer.

  • @justinjames3028
    @justinjames3028 2 года назад +4

    I did not understand std::move() until I watched this. To give some background, I was first exposed to C++ in 1994 but moved away from it before r-value references were a thing.
    I like the examples he provides. The problem I have with most explanations is that they use words like "tells the compiler it can cannibalize the object" or some such nonsense. That leaves the impression that the compiler is doing some type of cannibalizing or other magic behind the scenes.
    Saying it just turns the object to an r-value reference and as a side effect can cause the move constructor or move assignment operator to be called. The person cannibalizing is not the compiler, it is the implementor of those operations.
    After seeing this I wrote a simple class like he had and played around with it. It is not nearly as complicated as I thought.

  • @mikeweathers5726
    @mikeweathers5726 4 года назад +15

    Great video! This is my favorite C++ series. I hope you make one on perfect fowarding soon.

  • @johnnyserup5500
    @johnnyserup5500 2 года назад +3

    you definitely made a cool explanation of the std::move functionality - thanks, this is going to help many developers I think

  • @unmeinks5907
    @unmeinks5907 2 года назад +1

    after he said "implicit conversion and call into this specific string constructor" my furnature started floating, help

  • @jonathanp5195
    @jonathanp5195 2 года назад +8

    Thank you for the video. I think what "clicked" hardest for me was when I learned that the assignment operator, by default, only moves the values inside an object to a different object, if the object that it is being moved into pre-existed - which is why we overload the assignment operator, so that we can do this, even when the object that the data is being moved into is being initialized. Or at least, this is how I think it works. If I'm misunderstanding, I would love some clarification.

    • @astronautid7948
      @astronautid7948 2 года назад +3

      Good point! In a way the moving is the best thing that can happen to m_Data inside that operator. And we're talking the move assignment operator and the moving as opposed to copying which is what memcpy does in the copy constructor.This line says it all:
      m_Data = other.m_Data;
      Don't get disillusioned, however, thinking the data is being copied here. It's only a pointer being copied to another pointer. Imagine m_Data (in other) points to a char array the size of like billion. The array needn't to be copied, it stays where it was in memory. That's when we like assignment by move better than by copy. And we for this reason overload the move assignment operator. You got the gist.

  • @spicy_wizard
    @spicy_wizard 4 года назад +13

    perfect forwarding ~

  • @deepikagoyal07
    @deepikagoyal07 Год назад

    Move semantics is a topic difficult to comprehend. Your in depth explanation made it very clear.

  • @xi_the_pooh
    @xi_the_pooh 3 года назад +10

    Maybe covering std::forward here as well would've been a good idea, since they're somewhat related.

    • @Evan490BC
      @Evan490BC 3 года назад +1

      Yes, I was going to suggest the same.

    • @JorgeLuis-ts6qp
      @JorgeLuis-ts6qp 2 года назад +1

      Would you recommend any particular resource to learn that?

  • @varuntaneja7073
    @varuntaneja7073 4 года назад +29

    I don't earn right now so can't really support you on patreon but the least I can do is watch all the ads on your videos :)

    • @kartikgarasia5685
      @kartikgarasia5685 3 года назад +4

      Man now I just feel bad.. I also should pause adblocker on this channel

  • @Rohith_E
    @Rohith_E 4 года назад +3

    Your examples make move semantics really easy to understand. Please explain copy and swap idiom too.

  • @marcobonizzi3628
    @marcobonizzi3628 3 месяца назад

    Well done the Cherno, excellent lesson to be learnt!!!

  • @alecmather
    @alecmather Год назад

    Please never stop making videos.

  • @davidm.johnston8994
    @davidm.johnston8994 3 года назад +4

    That's amazing, thank you so much Mr Cherno!
    By the way, a lot of what I know of C++ I've learned from you, so a huge thanks, this has been very helpful!
    (Shoutout to Corey Schafer too for teaching me Python!)

  • @postdisc0
    @postdisc0 Год назад

    thanks for the difference between = and move constructor part, really never thought about it!

  • @igniculus_
    @igniculus_ 4 года назад +11

    I can't believe he is still making C++ videos. This just shows how much there is to know about C++ and how little I know ... :P

    • @lordmushroom723
      @lordmushroom723 4 года назад +2

      it's because this language has become extremely bloated and a pain in the ass to work with

    • @alpyre
      @alpyre 4 года назад +2

      @@lordmushroom723 Words of wisdom. C++ has too many features to solve the issues that are there because of C++ itself.

    • @PflanzenChirurg
      @PflanzenChirurg 4 года назад +3

      @@alpyre not really, it has just its rules and every new standard makes it easyer to create decent code

    • @RWM_
      @RWM_ 3 года назад

      @@PflanzenChirurg Yes, like here when you must create specific constructors and operators :)

  • @alexstone691
    @alexstone691 4 года назад +2

    First time somebody explained this and i managed to understand it, thank you!

  • @coolbrotherf127
    @coolbrotherf127 Год назад

    The move command is extremely useful when using smart pointers. Moving vectors of unique pointers around without having to copy a bunch of stuff is extremely useful.

  • @anonb1150
    @anonb1150 3 года назад +2

    Amazing video! You taught me how to create a move constructor and move assignment operator for my matrix class! Thank you!

    • @vaibhavlohiya8396
      @vaibhavlohiya8396 2 года назад +1

      If you still have that code can you send me the github repo coz I'm interested. Thank you

  • @TheDada0106
    @TheDada0106 Год назад

    You're a legend, learning c++ with you is exciting !

  • @z0lol
    @z0lol 4 года назад +6

    great video! well explained.
    would be great having a video regarding Variadic functions :D

  • @ianpan0102
    @ianpan0102 4 года назад +1

    Incredibly helpful and enjoyable video -- thousand thanks Cherno!

  • @MarcosVinicius-bd6bi
    @MarcosVinicius-bd6bi Год назад

    Dude, you're amazing. Your videos are helping me a lot!

  • @s187v
    @s187v 2 года назад +1

    thank you

  • @learnprogrammingwithsean9010
    @learnprogrammingwithsean9010 4 года назад +4

    I've learned a lot from your vids, thanks for posting!

  • @thestarinthesky_
    @thestarinthesky_ 4 года назад +4

    Thank you Cherno. I enjoyed learning every second of this video and I realized that the pace you spoke today in this video was quite perfect! Not too fast! I appreciate that!🥰😍🥰😍🤗❤️

  • @farhan787
    @farhan787 4 года назад +3

    Cherno finally a new video for C++ series, thanks ♥️

  • @SirShrimpey
    @SirShrimpey 4 года назад +3

    Dope, some time ago I was looking for a nice explanation of move assignment operator and exisiting stuff was quite confusing, I could have used a tutorial like this.

    • @roboticsrecords
      @roboticsrecords 4 года назад +5

      I believe explanation in chapter 5 in "Effective Modern C++" by Scott Meyers is one of the best source I've read on this topic. I have a paper copy, but it seems you can find it for free on the internet.

  • @marcofeder6768
    @marcofeder6768 3 года назад +2

    Nice video. I like to think to std::move as a way to have an rvalue reference. I remember that Stroustrup wrote in "The C++ Programming Language" that the best name for std::move() would have been rval()

  • @SwissPhil02
    @SwissPhil02 Год назад

    this is really well explained! Wish I would have watched your series before my interview...

  • @SergeySuper_Silver
    @SergeySuper_Silver Год назад

    I'd like to add one more thing.
    In order to create an empty object (in this case String 'dest'), we need a default constructor which sets m_Size = 0 and m_Data = nullptr.

  • @apelsin3001
    @apelsin3001 Год назад

    Thank you much! very understandable!

  • @joebosah2727
    @joebosah2727 3 года назад

    Shall get there and will overcome
    Thank you, Cherno

  • @luyuanqi2960
    @luyuanqi2960 3 года назад

    Dude you are a live saviour

  • @paulchoudhury2573
    @paulchoudhury2573 Год назад

    Excellent presentation. Well organized and full of important details.

  • @Kaslor1000
    @Kaslor1000 4 года назад

    This is insane, back to my simple Java world

  • @adityanandagudi
    @adityanandagudi 2 года назад

    awesome!! Thanks buddy

  • @tiantianliu5958
    @tiantianliu5958 9 месяцев назад

    Great! keep going!

  • @simonmaracine4721
    @simonmaracine4721 3 года назад +1

    Now I realize that Rust is basically doing move semantics by default. And to do a deep copy, you have to clone() the variable.
    let mut dest = String::new();
    let simon = String::from("Simon");
    let other = String::from("other");
    dest = simon; // This is a move; simon is now gone
    println!("{}", simon); // Compilation error
    dest = other.clone(); // Both dest and other are available
    println!("{}", other);
    println!("{}", dest); // Works
    In C++ is the other way around. By default deep copying is used.

  • @myronkipa2530
    @myronkipa2530 Год назад

    Cpp devs learning basic rust concepts

  • @TheMR-777
    @TheMR-777 4 года назад

    Wow! Really Nice! Many Thanks 4 this concept!

  • @kelvinsmith4894
    @kelvinsmith4894 4 года назад +3

    Awesome work you’re doing here!!, do you plan on making videos on error handlings and file system read and write in C++?

    • @Raspredval1337
      @Raspredval1337 4 года назад +2

      file read and write is rather simple, use , open a file and use it as cout or cin

  • @sajjadkarbasi281
    @sajjadkarbasi281 2 года назад +1

    there is a problem here . you dont initiate the m_data value in default constructor so when you try to use move constructor and try to delete there is nothing to be deleted so why this still works ? not for me though. i use gcc so probably i'm missing something .

  • @ILoveSoImAlive
    @ILoveSoImAlive 6 месяцев назад

    perhaps would be correct to first say, that move is for performance optimization. there is nothing wrong with copying in most cases. performance optimizations must only be done based on performance requirements. there is no use of doing that where its not needed at all, because performance requirements are met anyways. it would make your product worse, because it would get more expensive, without getting perceivably and practically better. its like if I would put 30% more work into the car, by giving decorative painting to all the screws inside the car.

  • @jediflamaster
    @jediflamaster 9 месяцев назад

    Just swap the values in move assignment instead of setting to default. You can skip the whole "what if they're the same object" problem

  • @Mohammed24441
    @Mohammed24441 4 года назад +6

    A video on lifetime extension, return value optimization, forwarding...

  • @Dante3085
    @Dante3085 4 года назад +1

    i literally have been waiting and researching this the last few days. nice !

  • @sakithanavod9289
    @sakithanavod9289 4 года назад

    Cant wait till next video 😍

  • @aleksandarfranc1094
    @aleksandarfranc1094 3 года назад

    You are a legend man!!

  • @niekbeijloos8355
    @niekbeijloos8355 2 года назад

    Great Videos you make! Keep it up!

  • @VoidloniXaarii
    @VoidloniXaarii Год назад

    Thank you very much

  • @LahiruGunathilake
    @LahiruGunathilake 3 года назад +3

    Hi Cherno, can you please do a video about std::forward too ? Thanks for this.

  • @pavfrang
    @pavfrang 2 года назад +1

    What about the copy assignment operator? Do you ever use it?

  • @JaiHall
    @JaiHall 4 года назад

    Very insightful, thank you. 🙏🏿

  • @baldendoboriqua6391
    @baldendoboriqua6391 4 года назад +1

    Very humbling video.. I don’t know shit ... 😅 I have so much to learn

  • @xxdeadmonkxx
    @xxdeadmonkxx 4 года назад +2

    No one:
    Voice recorder: blinking green as Cherno say something

  • @buzzdx
    @buzzdx 4 года назад +6

    very good explanation, thanks. i used to struggle understanding move semantics. one question though: in the string destructor you used "delete m_data;" while in the move operator you used "delete[] m_data". since you allocated the memory using new[], i think the destructor should use delete [] too. however it's not crashing. does it make a difference really which one you use to delete?

    • @oracleoftroy
      @oracleoftroy 4 года назад +2

      It is undefined behavior. As you point out, he should be using operator delete[].

    • @SerBallister
      @SerBallister 4 года назад +2

      In the case of POD types there are no destructors so new and new[] behave the same in this case. For none POD classes/destructable classes the compiler/implementation does do some trickery like encode the number of objects belonging to the array so it can later call the destructors on them all. It is best practice to delete[] though as some compilers/implementations may not simplify array allocations (most compilers do, but that's not a guarantee!)

    • @oracleoftroy
      @oracleoftroy 4 года назад +3

      @@SerBallister It is undefined behavior and thus is illegal C++ and shouldn't be relied on. It might work on your machine, but not other machines, and not your machine tomorrow as compiler and standard library implementer figure out better ways to optimize your program.
      A simple example, an allocator might pool all allocations for a single byte into a pool of memory such that a call to `delete charptr;` would be assumed to come from this pool whereas `delete [] charptr;` would expect the object to be allocated in a different pool (perhaps a large object pool). As the implementer knows it is illegal to use `operator delete` for memory allocated with `operator new[]` they can avoid storing extra information that isn't needed for a legal program and are under no obligation to properly cleanup programs relying on undefined behavior.
      Being a primitive type or not having a constructor isn't a reason to accept undefined behavior in a program.

  • @JATmatic
    @JATmatic 4 года назад +3

    Rule of five.. rule of five!
    Please, explain this and do the string class with copy-ctor && swap() idiom! :)

  • @poganka45
    @poganka45 Год назад +2

    For me the code crashes in debug mode. On line 96 dest is constructed with default constructor, but it doesnt initialize the private members on the lines 60 (char* m_Data) and 61 (uint32_t m_Size), so when dest.Print() is called on line 101, the for loop on line 54 actually starts - because unitialized m_Size is a garbage value, and m_Data[i] (which is a nullpointer) causes the crash.
    So i think char* m_Data should be set to nullptr uint32_t m_Size to 0.

    • @afterlife1578
      @afterlife1578 Год назад +1

      any idea why it worked for him? crashed on mine too

  • @jackofnotrades15
    @jackofnotrades15 4 года назад +3

    Could you do a video on streams? iostream and fstream class heirarchy and some stream handling functions?

  • @etinosaizekor6533
    @etinosaizekor6533 2 года назад

    Awesome!

  • @charlesmola
    @charlesmola 4 года назад +2

    Maybe you can do a video about Hash Tables!! it would be very useful. Thanks for the videos btw, they help me a lot

  • @Upload2971
    @Upload2971 3 года назад +2

    Why don't you share these example codes so that we can execute and experiment easily ? Thanks

  • @igorszemela1610
    @igorszemela1610 2 года назад

    great vid

  • @reza-nr2es
    @reza-nr2es 4 года назад +2

    wow the way i never knew that std::move is just a small template function which just simply does the casting thing for us...and all that casting does is calls the move constructor...the lazy and dumb me never tried to look up the definition of that std::move function....now i know...thanks cherno!!! but actually have a question...in order to use the move constructor, do we always explicitly have to tell the compiler by casting the type into a rvalue ref??? or there are cases where the compiler does it implicitly??? thanks in advance!!!

  • @marioterresdiaz6001
    @marioterresdiaz6001 2 года назад +1

    Great video!
    Got a question though, is it possible/recommended avoiding copying when the object is returned?

  • @lukenukem8028
    @lukenukem8028 4 года назад

    Knowing what to type is the complicated part.

  • @GuruPrasanna
    @GuruPrasanna 2 года назад +1

    9:42 instead of doing a manual delete[], isn't it better to simply transfer ownership of this->m_Data to the temporary? That way it will get deleted when the temporary is destructed?
    const auto otherSize = other.m_Size;
    const auto otherData = other.m_Data;
    other.m_Size = m_Size;
    other.m_Data = m_Data; // Will get deallocated on other's destruction
    m_Size = otherSize;
    m_Data = otherData;

  • @lucagagliano5118
    @lucagagliano5118 4 года назад +2

    I understand the basic idea. But I can't really figure a realistic case where I need to implement these explicitly. Usually you want to avoid heap allocation and people use a lot the stl library. Unless you're writing your own library I can't really picture a situation where you need to implement move constructors and move assignment explicitly. You also have default move constructors, but I don't know how they works.

    • @UsernameUsername0000
      @UsernameUsername0000 Год назад

      2 years late. You’re right that the STL encapsulates functionality. In cases where your class is composed of STL containers and/or smart pointers, then the default move constructor generated by the compiler would suffice. It does a member-wise move of all the members. If you use modern C++ and are more of a consumer than a creator, then you would likely never have to explicitly define those functions. Still, it’s good to be aware of the specifics of move semantics to allow you to leverage them well.

  • @oraz.
    @oraz. Год назад

    Using the initializer String string = "hello" with implicit conversion is a confusing addition.

  • @carnaqe1154
    @carnaqe1154 9 месяцев назад +1

    how can you Print the uninitialized m_data member without an error?

  • @AbhishekKumar-el3ls
    @AbhishekKumar-el3ls 9 месяцев назад +1

    While overloading the move assignment operator, should we not allocate memory for m_Data? If the destination string length is greater than the original string we are moving into, there would be a memory access violation.
    String orig = “Hello”;
    String dest = “LongerString”;
    orig = std::move(dest);
    can somebody explain?

  • @AbdullahJirjees
    @AbdullahJirjees 3 года назад +1

    Hello and thank you for the video I am having this question assignment can anyone help me in this issue?
    interval_map is a data structure that efficiently associates intervals of keys of type K with values of type V. Your task is to implement the assign member function of this data structure, which is outlined below.
    interval_map is implemented on top of std::map. In case you are not entirely sure which functions std::map provides, what they do and which guarantees they provide, we provide an excerpt of the C++ standard here:
    Each key-value-pair (k,v) in the std::map means that the value v is associated with the interval from k (including) to the next key (excluding) in the std::map.
    Example: the std::map (0,'A'), (3,'B'), (5,'A') represents the mapping
    0 -> 'A'
    1 -> 'A'
    2 -> 'A'
    3 -> 'B'
    4 -> 'B'
    5 -> 'A'
    6 -> 'A'
    7 -> 'A'
    ... all the way to numeric_limits::max()
    The representation in the std::map must be canonical, that is, consecutive map entries must not have the same value: ..., (0,'A'), (3,'A'), ... is not allowed. Initially, the whole range of K is associated with a given initial value, passed to the constructor of the interval_map data structure.
    Key type K
    besides being copyable and assignable, is less-than comparable via operator<
    is bounded below, with the lowest value being std::numeric_limits::lowest()
    does not implement any other operations, in particular, no equality comparison or arithmetic operators
    Value type V
    besides being copyable and assignable, is equality-comparable via operator==
    does not implement any other operations
    You are given the following source code:
    #include
    #include
    template
    class interval_map {
    std::map m_map;
    public:
    // constructor associates whole range of K with val by inserting (K_min, val)
    // into the map
    interval_map( V const& val) {
    m_map.insert(m_map.end(),std::make_pair(std::numeric_limits::lowest(),val));
    }
    // Assign value val to interval [keyBegin, keyEnd).
    // Overwrite previous values in this interval.
    // Conforming to the C++ Standard Library conventions, the interval
    // includes keyBegin, but excludes keyEnd.
    // If !( keyBegin < keyEnd ), this designates an empty interval,
    // and assign must do nothing.
    void assign( K const& keyBegin, K const& keyEnd, V const& val ) {

  • @johnc4624
    @johnc4624 Год назад

    Your string(string&&) constructor assigns to members instead of initialising.
    Was that on purpose? (4:20)
    Haven't heard the rest - thanks for making the video :-)

  • @maniaharshil
    @maniaharshil 9 месяцев назад

    Please cover the forwarding and arguments decay too Thanks

  • @nexovec
    @nexovec 4 года назад +1

    That weird feeling when you move into yourself and refuse to do anything

  • @vrushaliterekar4030
    @vrushaliterekar4030 4 года назад +1

    I have learnt basic components of C++ as a beginner and have tried to search 1000 ways of learning C++ as I am a self-taught person. The next step many people suggest is to solve the problems but I have solved basic problems such as calculater and some basic problems. Please could someone could help me with what projects should I consider which are not too advanced. Also some examples would do. (I am reading Effective C++ as Cherno suggested in one of his videos)
    I'd be so so glad if someone could help me as mentor

  • @aadill77
    @aadill77 Год назад

    9:04 have we really created a memory leak? We reference m_data to new memory location. Which means the previous memory location is not referenced anymore and so that memory must get auto flushed/removed/ garbage collected right?

  • @nawnwa
    @nawnwa 2 года назад +1

    Everything was clearly explained, only place I could fully accep the use of std::move was in the Entity constructor with "String&& name" parameter, isn't name already a r-value reference of the type "String&&" in the member initializer list, why do we again have to convert it to an r-value reference using std::move?

  • @vitordeoliveira6139
    @vitordeoliveira6139 2 года назад +1

    FOR LINUX USERS OR PEOPLE WHO IS HAVING ERRORS IN THE CODE:
    JUST DO THAT IN THE BEGINING
    class String
    {
    private:
    /* data */
    char *m_Data = nullptr;
    uint32_t m_Size = 0;
    AND THAT ON THE PRINT
    void Print()
    {
    if (m_Size != 0)
    {
    for (uint32_t i = 0; i < m_Size; i++)
    {
    printf("%c", m_Data[i]);
    }
    }
    printf("
    ");
    }

    • @ankitbhandari5222
      @ankitbhandari5222 2 года назад

      can you explain why my default constructor cannot provide value to m_data and in terminal showing free(): invalid size error when I try to delete m_data

    • @vitordeoliveira6139
      @vitordeoliveira6139 2 года назад

      @@ankitbhandari5222 How is your code:
      is this way?
      private:
      /* data */
      char *m_Data = nullptr;
      uint32_t m_Size = 0;
      public:
      String() = default;
      String(const char *string)
      {
      printf("Created
      ");
      m_Size = strlen(string);
      m_Data = new char[m_Size];
      memcpy(m_Data, string, m_Size);
      }

  • @whythosenames
    @whythosenames 4 года назад +1

    1:48 the classes are bytesized... that was a little nerdy but yeah i liked it :)

  • @jorsch4689
    @jorsch4689 2 года назад

    I ran into a free() error while following along. Just in case someone else also gets something similar, here's how I fixed it.
    Error: free() invalid memory
    Compiler: gcc
    OS: Pop OS (Linux)
    Solution:
    Replace `String() = default` with a properly initialized default constructor.
    ```
    String()
    : m_Data {},
    m_Size {}
    {
    }
    ```
    This problem might happen intermittently because it is entirely dependent upon how the memory at the location assigned is configured at the time.

  • @Gurman8r
    @Gurman8r 4 года назад +2

    another option is implementing move constructor/assignment in terms of a member swap function.

  • @HolyBucketsYT
    @HolyBucketsYT 3 года назад

    This begs the question of why should you EVER go back to using copy constructor when an object requires allocated data if deleting and reallocating data would always be burdensome?
    General rule, if your class makes use of "new" use move constructor, else just use copy constructor?

    • @HolyBucketsYT
      @HolyBucketsYT 3 года назад

      @Peterolen that would be an argument in favor of my point. Move operation preserve the object - copy construction must rebuild a new object. So I ask why ever copy construct?

    • @HolyBucketsYT
      @HolyBucketsYT 3 года назад

      @Peterolen ah, yes, I feel quite silly now... If you actually want to make a "copy" then the copy constructor is quite useful. Duh. Thanks!

  • @ericjovenitti6747
    @ericjovenitti6747 Год назад

    So one you’re an absolute amazing teacher and thank you for doing us, too maybe give use case examples for this I still factor five years don’t completely understand the best used cases for this. Is this more conducive for embedded systems or extremely low latency code?

  • @shaiavraham2910
    @shaiavraham2910 4 года назад +23

    Fix the String destructor for the love of c++. It just hurts me to see this memory leak. He even says "Trying to delete an array" in 12:57 and doesn't notice the leak.

    • @deltarambo6230
      @deltarambo6230 4 года назад +2

      Are you talking about the missing [ ]. If this is what you mean, then I think (but I am not sure) that dropping the [ ] is not an enough reason for memory leak in this case because the deleted array consists of trivially-destructed elements of type 'char'.

    • @MatkoFaka
      @MatkoFaka 4 года назад +4

      @Jayanam Develop
      thats why you should use malloc/free
      c > c++

    • @__jan
      @__jan 4 года назад +9

      @@MatkoFaka that's why you should use neither and leave it to RAII/smart pointers

    • @__jan
      @__jan 4 года назад +2

      @Jayanam Develop that's why i said RAII/smart pointers, and not just smart pointers.

  • @ryanmcgowan3061
    @ryanmcgowan3061 4 года назад +16

    Cherno, I'd love to see a video on your thoughts on Rust.

    • @roboticsrecords
      @roboticsrecords 4 года назад +3

      Also probably D language. D lang has already been used by gaming industry in "Quantum Break". I am not aware of any uses of Rust in games, but would be curios to learn what gaming industry thinks about it.

    • @matteopossamai1103
      @matteopossamai1103 4 года назад

      @@roboticsrecords Firefox is written in rust. I know it's not a game but it's more than enough of a reason to talk about it, and also since a browser is such a resource intensive task it probably makes sense to build a game engine with it

    • @dieSpinnt
      @dieSpinnt 4 года назад

      @@matteopossamai1103 Just a side-note: Take a step back and look what you are using now. This massive resource hungry monster, polluted with backwards compatibility and security nightmares like javascript isn't really a clever starting point for a game(engine). I second @Vlad Tananaev's suggestion because D(dlang) is wonderful. But you need experience to show something. I don't know if we should annoy Yan with it.
      At all, a little "gfm:opengl" and a pinch of "dlangui" (these are D packages) -> ready is your game:)

    • @matteopossamai1103
      @matteopossamai1103 4 года назад +1

      @@dieSpinnt This channel isn't just about game engines. He has a C++ series with something like 90 videos iirc and rust is a language that actually tries to fill the same spot as c++, whereas D has a garbage collector. I don't even know what in my comment made you think this was about Firefox, it isn't. The point is that it is a language that is used in the industry in a way that is similar to c++. (Favourite language of stack overflow for the last 5 years, and maybe there is a reason for that). About dlang... this is just my ignorant opinion as someone who never used it, but since not a lot of people use it wouldn't it make sense to use another compiled language with garbage collector such as Go? What about D is so revolutionary?

    • @obinator9065
      @obinator9065 4 года назад

      matteo possamai Not so many parts of Firefox are written in Rust (The CSS Engine) but many are still implemented in C++, they are rewriting some more parts but that is a ginormous project and it’s gonna take some time because these code bases are big and complex.
      Microsoft is also looking into Rust right now as 70% of security issues usually are memory leaks.
      As far as gaming goes there’s the piston engine and amethyst. These are pretty usable in the current state.

  • @austinfritzke9305
    @austinfritzke9305 4 года назад

    That was a painfully forced product promotion.

  • @bo-ruju6388
    @bo-ruju6388 2 года назад

    10:12 I would prefer a static_assert to stop myself to even doing that

  • @judickaelsam3103
    @judickaelsam3103 5 месяцев назад

    Thank you so much. Can you do it for std:: forward please?

  • @kaa_pex
    @kaa_pex Год назад

    looks like rust lang from the box.