Move Semantics in C++

  Рет қаралды 311,078

The Cherno

The Cherno

Күн бұрын

Пікірлер: 444
@TheCherno
@TheCherno 4 жыл бұрын
Hope you all enjoyed the video! This is just the beginning of the Move Semantics Saga™, still to come is std::move, the move assignment operator, and more! Thanks for watching! ❤️ P.S. RELAX GUYS THE PS5 PART 2 VIDEO IS COMING TOMORROW
@nothingtosee226
@nothingtosee226 4 жыл бұрын
Do you have your own personal library of functions, classes, namespaces, etc? My professor told me that it's important for programmers to have their own tools which make their own methods easier.
@AtlasPrimeV
@AtlasPrimeV 4 жыл бұрын
ok
@platinoob__2495
@platinoob__2495 4 жыл бұрын
Excuse me, I know this is out of the point, but, do you know a way to turn off auto save in Visual Studio Community 2019?
@pratikpatil1383
@pratikpatil1383 4 жыл бұрын
Thanks for starting with Move Semantics.. looking forward for more about this..👍
@shaiavraham2910
@shaiavraham2910 4 жыл бұрын
Can you make a video about the rule of 3 and the rule of 5 and how to implement them properly?
@TiredLemonpie
@TiredLemonpie 4 жыл бұрын
I owe you a huge thank you ! I've been trying to understand what are lvalue and rvalue for quite a long time, and an even longer time for what the move semantic was all about, and I've finally understand it with your video. I'm in a big learning phase right now, and your channel is an awesome way to improve myself. Thanks for the good work !
@justman7656
@justman7656 12 күн бұрын
I truly love your channel, man I read a bunch of internet articles and watched couple of videos and NO ONE made it that clear and consistent way Thank you so much, i finally understood this stuff
@shah.kairav
@shah.kairav 3 жыл бұрын
In case anyone is wondering why there is only one "Destroyed" line being printed on Cherno's terminal, remember that his program halts due to "std::cin.get()". Once he presses Enter, he should see the other "Destroyed" message. Reason for two destroys: 1 where the hollow object is destroyed + 1 where the actual heap memory is deallocated. Hope this saves time for someone and helps!
@Mzkysti
@Mzkysti 3 жыл бұрын
Thanks, I was getting two "Destroyed" and was like what the heck ;). Then I debugged it and the first one is destroying object with size of 0 and data as null, so I actually deduced this somehow myself too...
@pnuema1.618
@pnuema1.618 2 жыл бұрын
yeah I was wondering! saved me some time!
@alecmather
@alecmather 2 жыл бұрын
Bless your soul...
@Mmmaris_Chan
@Mmmaris_Chan Жыл бұрын
it helps! should read the comment first before figuring it out myself🤣
@SergeySuper_Silver
@SergeySuper_Silver Жыл бұрын
Thank you very much for your comment! I was confused by the two destructors. But now I know that happens)
@nabeelsherazi8860
@nabeelsherazi8860 3 жыл бұрын
Holy shit. I thought I knew things. I don’t know anything. This channel has been such a blessing. Instant sub.
@toddwasson3355
@toddwasson3355 2 жыл бұрын
Thank you so much for this move semantic vid. This has been wildly helpful to me today. Love your channel, your C++ playlist is by far my favorite of all C++ content.
@Norhther
@Norhther 4 жыл бұрын
8:24 noexcept is important for performance reasons. In a talk I saw, the example presented was 60% faster using noexcept because of the nature of push_back operation in std::vector. So keep that in mind!
@IndyR0ck
@IndyR0ck 2 жыл бұрын
what's the talk you saw? :)
@torstein5
@torstein5 Жыл бұрын
@@IndyR0ck Probably this one: Back to Basics: Move Semantics (part 1 of 2) - Klaus Iglberger - CppCon 2019
@IndyR0ck
@IndyR0ck Жыл бұрын
@@torstein5 thx!
@DassVeryGood
@DassVeryGood 2 жыл бұрын
This makes way more sense than what was being taught to me, where we just pushed multiple of the same object into a vector with different values (i.e. vec.push_back(Move{10})... vec.push_back(Move{n})). Sure it works, but doesn't help with visualizing the need to use a move constructor or semantics. This video helps so much, it just clicked instantly after watching this!
@ericprincen3345
@ericprincen3345 3 жыл бұрын
My first professional language was C++, and I moved from it in 1998 when I started working in Internet / Social media. I've moved back to writing low level code on hardware again, and I've been enjoying your videos a great deal. C++ has come a long way, and you've made my transition back a very easy one. BTW, I love the Hazel stuff too. Last time I worked with 3D graphics was when bsp trees were a new thing (and "fingering John Carmack" was something that was regularly done...) Fun to see how far that has all gone. I'm not doing any graphics right now, but fascinated with amount of forward movement in the field over the past 25 years.
@Brahvim
@Brahvim 11 ай бұрын
Pointing fingers at sir John Carmack? Sounds like the DOS days to me! I'm sorry I'm asking this _TWO_ years later, but in your opinion, how fast is C++ at evolving? It is often called an ever-evolving language, and especially with us getting a new standard every third year, I, a beginner, feels the same way. Thoughts? I invite other veterans to answer, too!
@aqezzz
@aqezzz 4 жыл бұрын
Thank you for this video! This is one of my favorite series on KZbin and this is a topic that can be quite confusing but you simplified it beautifully. Great job and keep up the good work
@khoing1111
@khoing1111 4 жыл бұрын
Founding this channel is a god damn blessing for me. Why did I not know about you earlier? Probably spent my whole life of luck on this.
@Yupppi
@Yupppi Жыл бұрын
Some of the videos are really clear cut and understandable, but I must say that in this one I dropped the ball very quickly. In like 10 seconds there appeared 50 lines of code and multiple class with their methods, privates, publics, printf, memcpy, delete etc.
@alextiga8166
@alextiga8166 4 жыл бұрын
This C++ series will never run out of topics to make a video about :) I've got too many requests what to cover in next videos. For example Multithreading: it would take forever to make videos about threads, locks, lock-free synchronization, fibers, coroutines etc.
@godnyx117
@godnyx117 4 жыл бұрын
This didn't aged well...
@alextiga8166
@alextiga8166 3 жыл бұрын
​@@godnyx117 Oh yeah I expected this series to cover more advanced topics but had to do my own research on the topic instead. Still a very great series and the best C++ series there is on KZbin!
@chawnneal159
@chawnneal159 4 жыл бұрын
OMG! Ever since your view_string video, I've been obsessed with making my own string_view! After this video I was able to mimic some functionality via referencing the same memory! With some extra steps I can prevent writing! Thanks so much!!
@iiTzLamar
@iiTzLamar 4 жыл бұрын
m_Data = new char[m_Size] should be freed with delete [ ] m_Data; and not delete m_Data;
@gideonunger7284
@gideonunger7284 4 жыл бұрын
It should also be m_Size + 1 when allocating for the null terminator
@Spirrwell
@Spirrwell 4 жыл бұрын
@@gideonunger7284 Not necessarily. You don't need to store a null terminator if you know your string's size. Though it can be useful with C style string functions. But he should've used delete[] or maybe even allocated with a unique_ptr instead.
@txorimorea3869
@txorimorea3869 4 жыл бұрын
That is good advice in general, however in this case is not necessary because the destructor of char is a no-operation. In this specific scenario is not necessary to call the destructor of every object in the array by calling delete[].
@gideonunger7284
@gideonunger7284 4 жыл бұрын
@@Spirrwell yes sure if you don't work with any c string functions or pass that pointer to the outside it's fine. But it's still dangerous in c++ since the assumption of a char* is that it's null terminated. Rust doesn't use null termination but there it's the standard of the language so it's not a problem anywhere
@TheJackiMonster
@TheJackiMonster 4 жыл бұрын
@@gideonunger7284 It's already dangerous to assume the const char* passed to strlen() will be null terminated. In C++ a compiler might add a null character to such values in double quotes but a C compiler won't do that implicitly which makes sense because you will know the length of a constant array of chars in your code already as developer.
@abdullahamrsobh
@abdullahamrsobh 4 жыл бұрын
That video really came, when i needed it thanks Cherno
@BillThaPill
@BillThaPill 4 жыл бұрын
Need that part 2 reaction video bruh. U be preaching facts and I be feeling that. Keep up the good work my guy. Just run that reaction video for ya boy. You’re killing me Smalls
@nallaprakash6901
@nallaprakash6901 4 жыл бұрын
Man I was waiting for this from ages 😭😭😭😭, FINALLY Thanks Chernikov 😄
@JayAnAm
@JayAnAm 4 жыл бұрын
Wow, naming a parameter "string" is quite... courageous:-)
@ianpan0102
@ianpan0102 4 жыл бұрын
Unless you're using namespace std, it doesn't really matter.
@unsafecast3636
@unsafecast3636 3 жыл бұрын
@Artem Katerynych #include using namespace std; string string(string string) { string string = string; } int main() { string string = “string”; string(string); }
@barmetler
@barmetler 3 жыл бұрын
@@ianpan0102 Using namespace std is a cardinal sin anyway
@alphazero4587
@alphazero4587 3 жыл бұрын
@@unsafecast3636 Bruh Bruh(Bruh);
@НейтральныйМаппер-з2м
@НейтральныйМаппер-з2м 3 жыл бұрын
@@unsafecast3636 god
@cole-nyc
@cole-nyc 4 жыл бұрын
Great video! one comment though: When you heap-allocate an array you have to free it with 'delete[]' instead of 'delete'. Your code frees only the first element of the array.
@KishoreG2396
@KishoreG2396 4 жыл бұрын
Technically its UB with char* string literals
@charoniv5631
@charoniv5631 3 жыл бұрын
what really?
@tolkienfan1972
@tolkienfan1972 2 жыл бұрын
According to the standard, using delete instead of delete[] is UB. In practice, both delete and delete[] are simply forwarded to the libc function "free", and therefore end up behaving the same. Of course I an NOT advocating using delete instead od delete[], that would be terrible practice. But there isn't an implementation out there that only frees the first element. In fact there isn't a function you could use to only free the first element. Even realloc won't do that.
@Flinsch77
@Flinsch77 2 жыл бұрын
With `delete` instead of `delete[]`, the whole array gets freed, no problem so far, but only one destructor might be called: that of the first element. This doesn't matter in the case of a `char` array, but it can be relevant for more complex objects, which in turn might allocate their own memory (which would then have to be freed again).
@tolkienfan1972
@tolkienfan1972 2 жыл бұрын
@@Flinsch77 that is correct. Thanks for that
@Albert-lr7ky
@Albert-lr7ky 2 жыл бұрын
Very nice and excellent video!!! Tho I've got a small question: should we be usong "delete [ ] m_Data" in the destructor? Since it is created from "new [ ]"
@jamesbaguio2386
@jamesbaguio2386 Жыл бұрын
Yes, the program needs to clean the continuous block of memory allocated to m_Data.
@halaszka2949
@halaszka2949 3 жыл бұрын
I KISS YOUR EYES! I didnt unterstand it with my book, but then i found you. R Value Refenrences and Move Semantics are very usefull
@kamilkarwacki9590
@kamilkarwacki9590 4 жыл бұрын
I learned so much about it but still dont know how to use it. So happy to see that you do a video on it as you always go very deep into these topics.
@CacheTaFace
@CacheTaFace 4 жыл бұрын
Great explanation! BTW your hair looks great here
@hamdaman3593
@hamdaman3593 4 жыл бұрын
Yes the ps5 part 2 is coming this weekend, whose looking forward to that
@MKolbe-jh6yh
@MKolbe-jh6yh 4 жыл бұрын
THANK YOU MY FRIEND! YOU JUST SAVED MY SEMESTER :D
@john_codes
@john_codes 4 жыл бұрын
Everyone: RELEASE PT 2 OF THE PS5 REACTION VIDEO Cherno: Here's a c++ move semantics video. Lol just kidding. I know he's releasing the video on Saturday. Can't wait!
@redscorpion9325
@redscorpion9325 4 жыл бұрын
John True Statement,this popped up and I was like where PS5 part 2 video everyone is waiting for😁
@redscorpion9325
@redscorpion9325 4 жыл бұрын
How do you know its being released on Saturday?
@Optamizm
@Optamizm 4 жыл бұрын
@M. de k., could be the Discord?
@john_codes
@john_codes 4 жыл бұрын
@@redscorpion9325 go to his channel and look at his community post. He said it's coming on Saturday:)
@RenatRakhmatullin
@RenatRakhmatullin 4 жыл бұрын
4:40 should be delete [ ]
@TernaryM01
@TernaryM01 4 жыл бұрын
He should've tested it on PVS-Studio to see if it can detect the memory leak.
@abdallahrashed1947
@abdallahrashed1947 4 жыл бұрын
what is the difference ?
@Zatmos
@Zatmos 4 жыл бұрын
@@abdallahrashed1947 "delete" destroys a dynamically allocated object and "delete[]" destroys a dynamically allocated array
@jinchengzhang25
@jinchengzhang25 4 жыл бұрын
@@TernaryM01 underrated comment lol
@ameynaik2743
@ameynaik2743 2 жыл бұрын
Take aways 1. Move constructor takes rval reference. 2. Instead of type casting var to rval using (T&&) var, we can use std::move(var) const T & takes both rval and lval but if rval is provided to this, it calls copy constructor because intermediate temporary variable is created. To avoid this we use move constructor.
@_Omni
@_Omni 2 жыл бұрын
Casting to xvalue
@supersquare
@supersquare 4 жыл бұрын
Thank you so much Cherno!! You're seriously the best 😊
@giannitedesco6153
@giannitedesco6153 4 жыл бұрын
You can do printf("%.*s ", (int)m_Size, m_Data); rather than that printf loop - it's easier, more efficient, and won't b0rk when you call it from multiple threads since the single call will happen under the stdout lock.
@xYuki91x
@xYuki91x 4 жыл бұрын
Yesss, I've been waiting for this, THANK YOU :) Will you make a video on Return Value Optimization in the future? I don't really get that topic, my professors aren't good at explaining, but you are
@Sala-lh9fu
@Sala-lh9fu 4 жыл бұрын
Thank you so much fir being so thorough with your explanations! :)
@radioactive5882
@radioactive5882 3 жыл бұрын
Move semantics is basically the same thing as what Patrick said from sponge-bob. Why don't we just move the bikini bottom. In other words, moving a large object without copying it. It would be a real pain to build a town, rebuild it somewhere else, and tear the old one down. Thanks btw, your videos semantics and R/L values really helped me out a lot. Would have probably given up on my textbook if I hadn't seen this video. The moment I realized how R and L values worked was when you mentioned the phrase "Location Value". All the rules suddenly clicked. I realized L values were like vacant houses for variables. When you assign 10 to x, you are assigning the value of 10 (an R value) to a memory location (l value). Reference variables allow you to sort of bend the rules a bit...
@rafalmichalski4893
@rafalmichalski4893 4 жыл бұрын
Less typing with "puts" (it adds ' "), so no need to use printf only to print non-formatted string with " " at the end. Anyway great material Cherno.
@AllothTian
@AllothTian 4 жыл бұрын
It's worth noting that we need to make the moved-from string "hollow" because its original constructor will still fire. In essence, a moved-from object can have multiple instances of its destructor being fired. This, as you can imagine, is rather inefficient. The alternative is what's called a "destructive move," but the design committee of the language couldn't figure out a way to make that fit with the existing object model. For the curious, you can look up Howard Hinnant's and Sean Parent's posts on this matter.
@ישראליעקובוביץ
@ישראליעקובוביץ 2 жыл бұрын
u give a human touch to a very dry and difficult topic , very helpfull
@JJFoxLegacy
@JJFoxLegacy 4 жыл бұрын
Dude loved the ps5 video, can't wait for the next part !!!
@Nick-tv5pu
@Nick-tv5pu Жыл бұрын
Great video, I always look forward to your stuff. That said, at 0:53 isn't that what references (pointers) are for? You don't have to copy a value to/from a function if you just pass/receive a pointer?
@aubertducharmont
@aubertducharmont 3 ай бұрын
Great video. Hope you one day also cover std::forward, since it is also very important for these semantics.
@shubham91219
@shubham91219 4 жыл бұрын
Hey Cherno, could you please make some videos on lock free programming and memory ordering as well? Thanks for all the great content so far.
@KishoreG2396
@KishoreG2396 4 жыл бұрын
Memory ordering is a very tricky subject.
@jh-lp7cg
@jh-lp7cg 4 жыл бұрын
Also, I believe any time the compiler can use Return Value Optimization do not try to use move semantics for return values. RVO will be more efficient.
@lmnefg121
@lmnefg121 4 жыл бұрын
really love your videos and i have learn a lot things from them
@267praveen
@267praveen 4 жыл бұрын
Finally ... It's here. Thanks Cherno. Next awaited ..... Regex SFINAE Random engines
@gvcallen
@gvcallen 4 жыл бұрын
I don't think I've ever been so excited to watch a C++ video before xD. They should put you on Netflix Cherno! ;)
@delulu6969
@delulu6969 4 жыл бұрын
I'm new to coding/programming. I started with JS and PHP. Along the way I learn OOP, and design patterns. Accidentally, I learn to understand Java and C++ syntax thanks to KZbin video suggestions like this. Thank you!😊
@maniaharshil
@maniaharshil Жыл бұрын
This is freaking greatest explanations ever for move sementic with demo : this explains whats going on underneath actually!! And how move sementic helpful in performance
@adamhendry945
@adamhendry945 Жыл бұрын
At 5:15, can you confirm, do we need the copy constructor because the default `String` constructor will only copy the `m_Data` pointer, but not its contents (as you mentioned in your Copy Constructor video)? I was a little confused at first because `String m_Name` in `Entity` is not a pointer.
@DIYGuy85
@DIYGuy85 4 жыл бұрын
Can someone please give this guy an award!
@alecmather
@alecmather 2 жыл бұрын
One thing I ran into while going through this video (apologies for my novice) is that you're using this shorthand syntax to assign the Entity->m_Name property in the constructor by doing ": m_Name(name)". Out of curiosity, I tried doing it the way I'm familiar with (just a normal "m_Name = name") inside the body of the Entity constructor, and this caused an error in the destructor of the String class. No idea why/how these two property assignments are different, probably worth an explanation somewhere? Thanks again for making awesome videos!
@alexandrumarcel3696
@alexandrumarcel3696 2 жыл бұрын
the difference between ":m_Name(name)" outside of the actual Constructor body and "m_Name = name" is that the first one is calling the Copy Constructor and the second one is calling the Operator = of the String class. Since there is no overloaded version of the operator = the compiler uses the default version provided by the compiler, but as the compiler doesn't know how you want to treat your pointer variable (m_Data) it just simply doing a shallow copy. So "m_Name = name" is basically assigning the pointer name.m_Data to m_Name.m_Data (m_Name.m_Data = name.m_Data), which will result in both name and m_Name pointing to the same address. So when "name" goes out of scope and the Destructor gets called, this will result in "m_Name.m_Data" being a dangling pointer, so when the m_Name object's Destructor gets called it will try to delete the pointer m_Name.m_Data which has been previously deleted when "name" got out of scope. Or at least this is I think happened :D Try to overload the operator = if you want to use the "m_Name = name" version
@alecmather
@alecmather 2 жыл бұрын
@@alexandrumarcel3696 you're a G for this explanation lol I also found that he later does a whole video on this difference which also helped a lot, thank you!!
@grownupgaming
@grownupgaming 2 жыл бұрын
Great video, very clear!
@AugusteeeJoJo
@AugusteeeJoJo 3 жыл бұрын
This is amazing! Thanks!
@musicplaylist3550
@musicplaylist3550 4 жыл бұрын
These videos are here to stay to help people even 5+ years from now 😨
@Omnifarious0
@Omnifarious0 4 жыл бұрын
You missed pointing out that if you have a true temporary it will also use the move constructor without needing ::std::move
@poggly
@poggly 4 жыл бұрын
This helped a lot, thank you!
@HamidMehr
@HamidMehr 2 жыл бұрын
So after attempting to learn move semantics/rvalue references for n times ( n >= 100) this finally clicked. Thanks, Cherno!
@oraz.
@oraz. Жыл бұрын
I think this topic would be less confusing if it was discussed as "move constructors" from the start instead of move semantics.
@B4dD0GGy
@B4dD0GGy 4 жыл бұрын
entertaining while *learning*, love it
@mikewajda9912
@mikewajda9912 4 жыл бұрын
Just found you channel and watched almost all of your c++ videos and some of your game engine series. Awesome job and thank you! Wanted to ask how you feel about rust compared to c++ and if you have had any experience with rust at all?
@karandutt4534
@karandutt4534 3 жыл бұрын
Hello Cherno, please keep uploading new features of C++ 11/14/17/20. Your content is great.
@Ximaz-
@Ximaz- Жыл бұрын
I really enjoyed your video, thanks.
@therealgunny
@therealgunny 4 жыл бұрын
move semantics are a great addition to c++ imo. i really like the approach that the committee has taken with c++. they are trying to make it more user friendly for new comers. great video btw.
@gideonunger7284
@gideonunger7284 4 жыл бұрын
Move semantics in c++ are a terrible mess though. Compared to move semantics in rust it's so overengeneered, complicated and also worse to use.
@therealgunny
@therealgunny 4 жыл бұрын
@@gideonunger7284 tbh if you compare c++ to most of the languages, it's a mess, i'm an avid c# user besides c++ and i know what you mean.
@benhetland576
@benhetland576 4 жыл бұрын
Move semantics is really not much more than fancy syntax sugar for pointer management behind the scenes IMO. Ownership of heap-allocated data is perhaps the most crucial issue to retain a clear overview over in order to stear clear of producing an app full of memory leaks (or the opposite: double-freeing). In languages with automatic built-in memory mgmt this challenge is attempted solved with a different philosophy than in C++ with its direct mem.mgmt, and that may well justify hiding those details from the programmer there. But with direct mem.mgmt hiding such details just appears to falsely relieve the programmer from that concern which they really ought not, and should not, forget about, ever! Thus, an unaware coder is easily mislead into not caring so much about it as they probably should; there is a loss of awareness. One got more direct control of mem.mgmt with a potential for better performance and flexibility, but with that potential also comes risks and responsibilities. In light of this I personally think we would be better off without the feature, as the smart pointers actually provide the same solution except you can better see what is actually going on. Move semantics actually cannot completely avoid copying in all cases anyway (consider objects on the stack as well as the underlying ptr to heap memory, for example), and it also introduces a nasty side-effect in that it may leave the source object in a limbo state while it is still technically accessible and within scope of the code. While such use is declared illegal/undefined, it is something that becomes all too easy to do by mistake. I guess I have just seen too many bugs arising from using uninitialized vars/objs over the years too feel comfortable in presence of any new feature with similar risks... It is not always that easy to know in an instance whether a move ctor or assignment was invoked instead of the corresponding copy ctor/asgmt ;-)
@TarunKumarSaraswat
@TarunKumarSaraswat 4 жыл бұрын
Wow❤️ simplified to the core
@yohan7027
@yohan7027 4 жыл бұрын
Should you use move with functions? Let's say: std::vector add( std::vector a, std::vector b) { ... } and I need to use whatever is passed into a and b later, is it better to pass by reference or move? I know that anything moved shouldn't be used again, so is there a way to move back after the function is done? Like making the parameter a const move or something? I ran some trials and move was faster than reference (is that true?) but it's pointless if it leads to undefined behavior.
@adityakolachana4621
@adityakolachana4621 9 ай бұрын
The way you added cast before bringing in std::move was really the way std::move should always be explained.
@TheZenytram
@TheZenytram 3 жыл бұрын
4:27 😲 he used printf( ); i cant believe it.
@sohankaushik7
@sohankaushik7 Ай бұрын
So do i
@beboba2498
@beboba2498 2 жыл бұрын
That's why other languages are simply using smart pointers, and C++ also has smart pointers, which are way more convenient and less prone to errors than move semantics
@RelayComputer
@RelayComputer Жыл бұрын
I was thinking exactly the same
@Swonkasaur
@Swonkasaur 4 жыл бұрын
Thank you for the free 2 months of skill share ;D
@josephlai7737
@josephlai7737 3 жыл бұрын
@11:31, why is std::move() necessary, even though in the function signature Entity(String&& name), name was specified to be a rvalue? std::move(name) converts a rvalue to a rvalue, and it just looks strange.
@anonymoussloth6687
@anonymoussloth6687 3 жыл бұрын
Same question
@charlesyin289
@charlesyin289 2 жыл бұрын
@@anonymoussloth6687 same question
@DipsAndPushups
@DipsAndPushups 2 жыл бұрын
This has finally clicked. It clicked only after I realized that copy constructors, move constructors etc. are just regular constructors which take in a const reference and an rvalue reference, respectively. My knowledge of Rust got in the way of understanding this at first. So, basically, if you want a constructor to take ownership of the existing data instead of copying it, the constructor should accept rvalue references. What's weird is that C++ seems to be different than Rust here. Rust's compiler doesn't allow you to use moved objects. As far as I understand in C++ you can go on and use objects even after casting them to rvalue reference and passing them to a constructor. Compiler will let you do it.
@NguyễnLong-o1t
@NguyễnLong-o1t 2 ай бұрын
thank you very much!
@muhammadaamirzaman
@muhammadaamirzaman 4 жыл бұрын
Top class teacher for Cpp
@crash1013
@crash1013 4 жыл бұрын
Many years ago when I learned K&R C, ignoring the NULL sentinel was one of the most painful programming lessons I learned. Bad things can happen if you don't allocate room for the NULL sentinel and then use C standard library string functions.
@tomwhitcombe7621
@tomwhitcombe7621 4 жыл бұрын
Literally just watched your lval rval video an hour ago. Good timing :)
@tannishkmankar3998
@tannishkmankar3998 2 жыл бұрын
Great you solved one headache for me, thanks
@GreenFlame16
@GreenFlame16 4 жыл бұрын
Hey, Cherno, the video after Static Analysis in C++ is now marked as private. Was that intentional? Or was it also on move semantics but now you're redoing it and thus removed the old one? Loving your content!
@Toccobass13
@Toccobass13 3 жыл бұрын
Thank you!
@filosofisto
@filosofisto 4 жыл бұрын
Excelent explanation, thank you
@nabil41854
@nabil41854 4 жыл бұрын
Thanks for the great explanation. I just have a note, you are moving the curser a lot making it a bit difficult to follow. cheers
@ckacquah
@ckacquah 4 жыл бұрын
Your videos always explain everything better 👍... Nice example
@vickoza1
@vickoza1 4 жыл бұрын
You made a mistake with the delete operator in the districtor. You need to uses the delete [] and not the delete witch will only delete one character.
@oracleoftroy
@oracleoftroy 4 жыл бұрын
It's undefined behavior, so all bets are off, but technically it would only call the destructor for the first item (which is meaningless for a char) and very likely delete all the memory. Which is basically the worst type of undefined behavior, everything works fine today, and tomorrow compiler writers figure out a way to get more speed and your code stops working.
@tmsaskg
@tmsaskg Жыл бұрын
Cherno, you could perfectly voice Mike Judge, several B&B characters including Butthead. Did anyone point that out? Quite good resemblance in this video!
@Idlecodex
@Idlecodex 4 жыл бұрын
Man... God bless you! :)
@shefman200
@shefman200 4 жыл бұрын
Ayo my g we respect your regular content...but we want that that ps5 part 2
@markf5931
@markf5931 3 жыл бұрын
At 1:06 you mentioned passing an object by value to a function, which invokes the copy constructor, thus is wasteful. I understand you are using this use case an example/motivation to explain move semantics. However, isn't the solution simply to pass the object by reference to the function, to avoid copy constructor/waste?
@andredesantacruz
@andredesantacruz Ай бұрын
What's wrong with having a reference parameter to the object you want to "create" and just modify it inside the given function? That way you don't have to return anything and the [out] object passed as an argument will be created or updated in the way you want.
@RaonCreate
@RaonCreate 3 жыл бұрын
well done explained
@sumitgupta7553
@sumitgupta7553 Жыл бұрын
Hi Cherno, you are just amazing.. Well described. But can you help me in finding out where I'm getting wrong, when I say we can do the work, you done in move constructor, in the copy constructor even in that constructor we only getting reference of the object, then what is the need to define separately!
@indramaniarora7901
@indramaniarora7901 3 жыл бұрын
Hey Cherno. One video on std::decay as well please
@upamanyumukharji3157
@upamanyumukharji3157 5 ай бұрын
hey can someone explain why the copy constructor is called if we do not use explicit type casting/std::move ? If the r-value ref entity constructor is called shouldnt name ref be of type String &&?
@mkhadka123
@mkhadka123 Жыл бұрын
Ok my head is spinning now
@stopfdenpc
@stopfdenpc 4 жыл бұрын
You can't even believe how requested this is. I literally just youtube searched for this topic because I thought I can't wait on cherno to make a video on this and it turns out you literally just uploaded one 5 hours ago.
@tannishkmankar3998
@tannishkmankar3998 2 жыл бұрын
Still working as of today, ty!
@bipingosain6870
@bipingosain6870 4 жыл бұрын
Greate Video! Can you please do a series or at least a video to give an overview of how to get started with Authoritative Multiplayer Code with C++?
@gabrielbraz9669
@gabrielbraz9669 Жыл бұрын
4:47 shouldn't he have used the delete[] operator instead? Also, couldn't I achive the same result using the copy constructor? If I use the same code of the move constructor inside the copy one, I would still be passing the pointer to the block of data and erasing the old pointer so it doesn't delete de buffer. Or am I wrong? But if you need both copy and move construtor to be on the same class, then I understand the need of it.
@mgancarzjr
@mgancarzjr 4 жыл бұрын
Fairly certain this conundrum was a chapter in Effective C++.
@platinoob__2495
@platinoob__2495 4 жыл бұрын
so basically this is for rvalues what reference parameters are for lvalues
@R3negade638
@R3negade638 4 жыл бұрын
Exactly. Its useful to avoid copies (which can be costly for large structures and heap allocations) for the times when what you really want is not a duplicate copy of an object's memory, but to hand off ownership of its memory to another object.
@timonsku
@timonsku 4 жыл бұрын
You break down things pretty well but I have to say that you are explaining at a really fast speed which makes it really hard to follow without constantly rewatching a part if you are not already familiar with the topic. Slowing down a little bit would be great :)
@alexandruoporanu8261
@alexandruoporanu8261 10 ай бұрын
When putting your code in an Online cpp compiler the "Destroyed" is printed twice. And that actually makes sense. I do not understand why in the video that happend only once.
@justingifford4425
@justingifford4425 5 ай бұрын
Because he paused the app with cin.get(). The second delete happens after that.
@CannibalPedroX94
@CannibalPedroX94 4 жыл бұрын
I thought I was starting to understand move semantics and move constructors, then I discovered something called Copy Elision and, well, now I am very confused hahahaah
@--ShivaS
@--ShivaS 4 жыл бұрын
lol
@--ShivaS
@--ShivaS 4 жыл бұрын
yea some compiler optimization bullshit
std::move and the Move Assignment Operator in C++
16:06
The Cherno
Рет қаралды 181 М.
Return Value Optimization and Copy Elision in C++
9:54
mCoding
Рет қаралды 40 М.
BAYGUYSTAN | 1 СЕРИЯ | bayGUYS
36:55
bayGUYS
Рет қаралды 1,9 МЛН
Beat Ronaldo, Win $1,000,000
22:45
MrBeast
Рет қаралды 158 МЛН
lvalues and rvalues in C++
14:13
The Cherno
Рет қаралды 333 М.
Weak Pointers in C++ (std::weak_ptr)
17:25
The Cherno
Рет қаралды 63 М.
Reacting to Controversial Opinions of Software Engineers
9:18
Fireship
Рет қаралды 2,2 МЛН
ITERATORS in C++
17:09
The Cherno
Рет қаралды 218 М.
What exactly is NULL?
18:06
The Cherno
Рет қаралды 197 М.
Re-inventing move semantics in modern C++ in 13 minutes
13:20
Code for yourself
Рет қаралды 7 М.
Stack vs Heap Memory in C++
19:31
The Cherno
Рет қаралды 590 М.
Writing an ITERATOR in C++
19:44
The Cherno
Рет қаралды 129 М.
Track MEMORY ALLOCATIONS the Easy Way in C++
13:25
The Cherno
Рет қаралды 168 М.