Return Value Optimization and Copy Elision in C++

  Рет қаралды 36,679

mCoding

mCoding

Күн бұрын

Embrace the copy-free lifestyle!
― mCoding with James Murphy (mcoding.io)
Source code: github.com/mCodingLLC/VideosS...
Cppref on copy elision: en.cppreference.com/w/cpp/lan...
SUPPORT ME ⭐
---------------------------------------------------
Sign up on Patreon to get your donor role and early access to videos!
/ mcoding
Feeling generous but don't have a Patreon? Donate via PayPal! (No sign up needed.)
www.paypal.com/donate/?hosted...
Want to donate crypto? Check out the rest of my supported donations on my website!
mcoding.io/donate
Top patrons and donors: Jameson, Laura M, Dragos C, Vahnekie, Neel R, Matt R, Johan A, Casey G, John Martin, Mutual Information
BE ACTIVE IN MY COMMUNITY 😄
---------------------------------------------------
Discord: / discord
Github: github.com/mCodingLLC/
Reddit: / mcoding
Facebook: / james.mcoding
CHAPTERS
---------------------------------------------------
0:00 Intro
0:40 Return Value Optimization
3:06 Where do the copies come from?
5:23 When can copies be elided?
7:46 C++17 mandatory copy elision
9:38 Thanks

Пікірлер: 80
@turgutbababalm9981
@turgutbababalm9981 Жыл бұрын
I was just learning more about this! Perfect timing and perfect tutorial as always. Please do more C/C++ content!
@l4luchi123
@l4luchi123 Жыл бұрын
I'm glad to see another C++ video from you. I hope there are more of these in the pipeline!
@Nikolas_Davis
@Nikolas_Davis Жыл бұрын
This reminds me of tail recursion in functional languages: a function calling itself recursively as its *last* action can have its context safely removed from the stack, and replaced by the context of the callee.
@bradywb98
@bradywb98 Жыл бұрын
This isn’t just in functional languages. Java, C++, C probably do it too depending on the optimization level.
@gelding
@gelding Жыл бұрын
Please continue creating C++ content. Incredibly resourceful and interesting. Would like longer videos also!
@Aleksandar0100
@Aleksandar0100 Жыл бұрын
the thing I like the most most about C++ is how simple and straight forward it is, no gotchas or special cases, what you see is what you get, it's amazing really
@firstname4337
@firstname4337 Жыл бұрын
LOL, what a load of crap -- it is literally the exact opposite -- did you not see the copy constructor that was marked as deleted and how it behaves differently in 11 and 17 ?
@Tomyb15
@Tomyb15 Жыл бұрын
@@firstname4337 thatsthejoke.jpg
@KappakIaus
@KappakIaus Жыл бұрын
amazing indeed 😂
@IronLotus15
@IronLotus15 9 ай бұрын
Your calm voice and intonation is great for these kinds of videos! I really appreciate these clean and concise explainations of concepts.
@bartlomiejodachowski
@bartlomiejodachowski Жыл бұрын
Your video cleared something about C++ i couldnt stop think that it's not exacly like good old C would normally do. It really helped me. Thank You ❤
@Sevenhens
@Sevenhens Жыл бұрын
The world would be a better place if C++'s constructor rules didn't make my stomach twist in anxiety. Non-default constructors invite the devil into your home, and you'd never rest easy knowing you may have accidentally missed a common gotcha and now there's 5 heap allocated std::strings under your bed.
@RohitSangubotla
@RohitSangubotla 10 ай бұрын
I understood practically nothing about copy elision from a lot of resources until I came across this video, and in ten minutes I was able to understand it fully. Thank you!
@RussBork
@RussBork Жыл бұрын
Thanks for the great videos James, you're the best programming channel on KZfaq. Always interesting and useful content explained clearly with no filler.
@ifgpuelse
@ifgpuelse Жыл бұрын
Thanks for share your knowledge with us!
@BetaNegative
@BetaNegative 8 ай бұрын
I love how flat the delivery of the humor is ("devolve into our primal spaghetti nature"). Very well done 👌
@ussgordoncaptain
@ussgordoncaptain Жыл бұрын
C++ is like piloiting a jet engine naked with an open cockpit.
@mCoding
@mCoding Жыл бұрын
Thank you for that imagery 😂
@AttaKru
@AttaKru Жыл бұрын
and here i am juggling with move assignments, and returning references to internal members, and complicating life cycles like madman
@tomatus270389
@tomatus270389 Жыл бұрын
Love your C++ videos
@zionen01
@zionen01 4 ай бұрын
Nice video. I was a bit stumped on 7:06 thinking it should be possible to move the value given both s1 and s2 are ephemeral values local to the function but then I remembered this is a compiler optimization, not a runtime optimization. So then I wondered if a simple design change to the code would work around such a case by doing the branching before calling the function. It's a interesting consideration that I wouldn't have thought to do before this, but it has performance implications.
@rajthewise
@rajthewise Жыл бұрын
Wish for more videos on C++ from you.
@thanhnguyennguyen9235
@thanhnguyennguyen9235 Жыл бұрын
Thank you for your video
@Yupppi
@Yupppi 6 ай бұрын
Sean Parent in one of his brilliant talks went through this kind of copy behavior (but in code that actually doesn't allow compiler to do it magic, being a code smell). Fascinating stuff.
@zeez7777
@zeez7777 2 ай бұрын
What a great video.
@jacklimestone2559
@jacklimestone2559 8 ай бұрын
I think I just experienced a bug at work in C# that was due to this copy elision. I was doing something other than copying in the copy constructor, and it wasn't being done! Thanks for opening my eyes!
@lamprospitsillou6325
@lamprospitsillou6325 Жыл бұрын
Yesss, more c++!
@lrdxgm
@lrdxgm Жыл бұрын
"Haven't said anything about move ops, but listing out more cases doesn't do anything good" - well, actually, every single one of your examples were calling MOVE, and not COPY constructor just your example S class' move constructor is the copy constructor (because you didn't implement a move, move is using the copy ctr).
@mCoding
@mCoding Жыл бұрын
I'm not sure what exactly your objection is here (perhaps you could elaborate?). Yes, the compiler will move returned local variables if a move constructor is available. No move was provided so it called the user-defined copy constructor. Are you saying I should still refer to this as a move even though the copy constructor was called and no move constructor is provided or generated by the compiler? I'm not sure I would agree with calling it a move in that situation, especially not colloquially. Colloquially, when one speaks of eliminating copies and eliminating moves, one is typically referring the act of reducing the number of times the copy constructor or move constructor actually gets called, i.e. an empirical reduction in copies or moves, not a reduction in places where the standard would allow a copy/move. In any case, it is not correct to say that the move constructor "is the copy constructor" if one is not provided. The definition of copy/move constructor in the standard is based on the signature of the function alone. It is *not* based on whether it is called when initializing from a prvalue. Instead, the compiler may chose to copy *instead of* move due to the fact that no move constructor is available.
@vladyslavkotov7570
@vladyslavkotov7570 Жыл бұрын
Hi James, what books\courses can you recommend on c++? Apart from Bjarne's books. Thank you!
@this-one
@this-one Жыл бұрын
Woah, I've never been this early!
@Ryan-xq3kl
@Ryan-xq3kl Жыл бұрын
awesome!
@firstname4337
@firstname4337 Жыл бұрын
this was an awesome video -- i learned C++ WAY BACK before the "modern age" and i really hated it but these required optimizations make it sound much better than i remember
@slpwrm
@slpwrm Жыл бұрын
don't be fooled, it's still horrible to actually code with
@Tibor0991
@Tibor0991 Жыл бұрын
@@slpwrm filtered, LMAO
@drnoob13
@drnoob13 Жыл бұрын
@@slpwrm not true for me. I actually enjoy writing modern C++ than C.
@julians.2597
@julians.2597 2 ай бұрын
@@drnoob13 I mean yes, but that bar is very low.
@ONIscrooge
@ONIscrooge Жыл бұрын
Good vid.
@darvil82
@darvil82 Жыл бұрын
C++ videos 🙏
@wChris_
@wChris_ Жыл бұрын
Now how does the function now the address of the variable? is this another case of a hidden function argument, just like this in classes?
@klaotische5701
@klaotische5701 Ай бұрын
So it's basically auto reference for all the function call?
@fejfo6559
@fejfo6559 Жыл бұрын
7:12 could the compiler inline the no_elusion function and then remove the redundant "if(27>0)" and then do copy elusion?
@anon_y_mousse
@anon_y_mousse Жыл бұрын
If you use the inline keyword or up the optimization level it should, but I'm not an expert on the C++ standard, so don't quote me on that.
@mCoding
@mCoding Жыл бұрын
A great one to test on compiler explorer! godbolt.org/z/rYq1ejzKW Even in C++23 at -O3 with "if (true)" we still see the copy. Note however that if you move the instantiations of s1, s2 inside the scope of the if block that they are actually returned in, then the copy can be elided because they will no longer interfere with each other.
@anon_y_mousse
@anon_y_mousse Жыл бұрын
It'd be nice if that rule were more clearly and concretely defined. Ideally it should always optimize it away, and in the case of the two values caught by control flow, while it couldn't always catch that, I hope modules mitigate some of the cases where it wouldn't. Obviously when taking user input to decide that control flow it will never optimize it away, but with a constant as in the example I hope it does.
@U20E0
@U20E0 Жыл бұрын
afaik, the compiler can’t do that - if a function is called ( explicitly ), it must be called. That optimization would mean you would be calling a different function.
@b4ttlemast0r
@b4ttlemast0r 6 ай бұрын
6:55 couldn't you arbitrarily choose one of either s1 or s2 to be constructed in the return value space, and then in the worst case if it ends up being the other one, you have to copy and overwrite it (shouldn't make performance worse if I'm not missing something) and in the best case you guessed correctly and you can elide the copy. The compiler could even try to figure out which branch is more likely and choose which variable to construct in the return value space based on that. I'm guessing that this optimisation isn't mentioned in the language standard, but would a compiler still be allowed to do it, at least if the elided copy constructor has no side effects?
@urielpelaezcdmx
@urielpelaezcdmx Жыл бұрын
What about the parallelism between Windows 10 (latest update) and C++ (20) compilers?
@spell105
@spell105 Жыл бұрын
What are you implying here?
@richardmetzler7909
@richardmetzler7909 Жыл бұрын
Thanks for this video, it reminds me how lucky I am, having left behind C++ for now to work in a sane language.
@mCoding
@mCoding Жыл бұрын
Hahaha what is your language of choice now?
@Roule_n_Scratche
@Roule_n_Scratche Жыл бұрын
@@mCoding In my case, I've ditched C++ after learning about Rust, at least for me, Rust is just C++ minus the enormous headaches that came with the language. I was using C++ for only 2-3 months or so, it's kinda funny how I switched languages so quickly.
@Tibor0991
@Tibor0991 Жыл бұрын
Nice way to tell the world you're too bad for real languages.
@richardmetzler7909
@richardmetzler7909 Жыл бұрын
@@mCoding Python.
@richardmetzler7909
@richardmetzler7909 Жыл бұрын
@@Tibor0991 LOL. I've spent more than a decade with C++, I just got tired of dealing with the pointless obstacles that it puts in the developer's way for no good reason. You've got an "object oriented language" with a "standard library", but you can't use actual objects or types from the standard library in the public interface of your library unless the user happens to use the same compiler? Get outta here.
@AhrkFinTey
@AhrkFinTey Жыл бұрын
james murphy? like from lcd soundsystem?
@mCoding
@mCoding Жыл бұрын
Same names, different James!
@mehdi-vl5nn
@mehdi-vl5nn Жыл бұрын
spaghetti code is more about Goto continue and break (loop type of thing !)
@trag1czny
@trag1czny Жыл бұрын
discord gang 🤙🤙
@qexat
@qexat Жыл бұрын
hi mod
@kashgarinn
@kashgarinn Жыл бұрын
Surprised there isn’t a comparison to const byref
@ilyam.1872
@ilyam.1872 Жыл бұрын
KZfaq subtitle generation algorithm wasn't optimized enough to understand “copy elision”
@adivp7
@adivp7 Жыл бұрын
I'm not that great at c++.If someone can help me, one of the problems I face often is the hash for a few template types just aren't defined. For example if I want to put a pair of ints or a tuple of ints in an unordered_map as keys, I can't do it. Any easy ways to get around this?
@dhkatz_
@dhkatz_ Жыл бұрын
The easiest way is to just define your own hash function, for example, for strings you could do: #include #include #include typedef std::pair pair; struct pair_hash { template std::size_t operator() (const std::pair &pair) const { return std::hash()(pair.first) ^ std::hash()(pair.second); } }; int main() { std::unordered_map unordered_map = { {{"C++", "C++11"}, 2011}, {{"C++", "C++14"}, 2014}, {{"C++", "C++17"}, 2017}, {{"Java", "Java 7"}, 2011}, {{"Java", "Java 8"}, 2014}, {{"Java", "Java 9"}, 2017} }; for (auto const &entry: unordered_map) { auto key_pair = entry.first; std::cout
@damnstupidoldidiot8776
@damnstupidoldidiot8776 Жыл бұрын
Extend std::hash, if nobody else is going to use your code.
@tatianaes3354
@tatianaes3354 Жыл бұрын
What does “vroom vroom” mean? Sounds cute, though.
@mCoding
@mCoding Жыл бұрын
It's the sound a car makes revving its engine!
@dmitrystelefona8453
@dmitrystelefona8453 8 ай бұрын
Huh? 2:33
@parlor3115
@parlor3115 Жыл бұрын
For people saying that Rust is now as complex as C++
@chriskeo392
@chriskeo392 Жыл бұрын
I miss Python content
@motbus3
@motbus3 Жыл бұрын
C++ being c++
@markcuello5
@markcuello5 Жыл бұрын
HELP
@31redorange08
@31redorange08 Жыл бұрын
5:20 Stolen from Kaze Emanuar!
@mCoding
@mCoding Жыл бұрын
You caught the reference! I love his videos!
@31redorange08
@31redorange08 Жыл бұрын
@@mCoding I knew it was a reference because I saw your comment on his video. 😉
@i007c
@i007c Жыл бұрын
and thats why cpp is considered as BS language C forever 🤣🤣
@poetryflynn3712
@poetryflynn3712 Жыл бұрын
Honestly, what he showed is quite irrelevant to how you code in Cpp. Why? Because you would never do what he did here. I can not think of any context this knowledge would be useful.
@Kurkkulimu
@Kurkkulimu Жыл бұрын
Why should you make copies, if you did not need one? You understand that some objects might be really heavy to copy right?
@anon_y_mousse
@anon_y_mousse Жыл бұрын
@@Kurkkulimu I think he means because you don't have to jump through hoops to avoid unnecessary copying as well as to make the compiler generate optimized code.
Interviewing the creator of C++, Bjarne Stroustrup
14:45
mCoding
Рет қаралды 33 М.
31 nooby C++ habits you need to ditch
16:18
mCoding
Рет қаралды 725 М.
ДЕНЬ РОЖДЕНИЯ БАБУШКИ #shorts
00:19
Паша Осадчий
Рет қаралды 7 МЛН
The Worlds Most Powerfull Batteries !
00:48
Woody & Kleiny
Рет қаралды 28 МЛН
C++ cache locality and branch predictability
10:43
mCoding
Рет қаралды 77 М.
The ONLY C keyword with no C++ equivalent
13:17
mCoding
Рет қаралды 265 М.
Advanced Topics: Copy Elision
9:46
CoffeeBeforeArch
Рет қаралды 3 М.
Async for loops in Python
16:36
mCoding
Рет қаралды 57 М.
Rust Functions Are Weird (But Be Glad)
19:52
Logan Smith
Рет қаралды 126 М.
All 71 built-in Python functions
19:58
mCoding
Рет қаралды 40 М.
Conversion Operators in C++
19:56
The Cherno
Рет қаралды 34 М.
why do void* pointers even exist?
8:17
Low Level Learning
Рет қаралды 322 М.
Why You Shouldn't Nest Your Code
8:30
CodeAesthetic
Рет қаралды 2,6 МЛН
Интереснее чем Apple Store - шоурум BigGeek
0:42
📦Он вам не медведь! Обзор FlyingBear S1
18:26
i love you subscriber ♥️ #iphone #iphonefold #shortvideo
0:14
Si pamerR
Рет қаралды 2,6 МЛН
TOP-18 ФИШЕК iOS 18
17:09
Wylsacom
Рет қаралды 606 М.