C++ Weekly - Ep 380 - What Are std::ref and std::cref and When Should You Use Them?

Sdílet
Vložit
  • čas přidán 11. 06. 2023
  • ☟☟ Awesome T-Shirts! Sponsors! Books! ☟☟
    Upcoming Workshop: Understanding Object Lifetime, C++ On Sea, July 2, 2024
    ► cpponsea.uk/2024/sessions/und...
    Upcoming Workshop: C++ Best Practices, NDC TechTown, Sept 9-10, 2024
    ► ndctechtown.com/workshops/c-b...
    Discussion: github.com/lefticus/cpp_weekl...
    T-SHIRTS AVAILABLE!
    ► The best C++ T-Shirts anywhere! my-store-d16a2f.creator-sprin...
    WANT MORE JASON?
    ► My Training Classes: emptycrate.com/training.html
    ► Follow me on twitter: / lefticus
    SUPPORT THE CHANNEL
    ► Patreon: / lefticus
    ► Github Sponsors: github.com/sponsors/lefticus
    ► Paypal Donation: www.paypal.com/donate/?hosted...
    GET INVOLVED
    ► Video Idea List: github.com/lefticus/cpp_weekl...
    JASON'S BOOKS
    ► C++23 Best Practices
    Leanpub Ebook: leanpub.com/cpp23_best_practi...
    ► C++ Best Practices
    Amazon Paperback: amzn.to/3wpAU3Z
    Leanpub Ebook: leanpub.com/cppbestpractices
    JASON'S PUZZLE BOOKS
    ► Object Lifetime Puzzlers Book 1
    Amazon Paperback: amzn.to/3g6Ervj
    Leanpub Ebook: leanpub.com/objectlifetimepuz...
    ► Object Lifetime Puzzlers Book 2
    Amazon Paperback: amzn.to/3whdUDU
    Leanpub Ebook: leanpub.com/objectlifetimepuz...
    ► Object Lifetime Puzzlers Book 3
    Leanpub Ebook: leanpub.com/objectlifetimepuz...
    ► Copy and Reference Puzzlers Book 1
    Amazon Paperback: amzn.to/3g7ZVb9
    Leanpub Ebook: leanpub.com/copyandreferencep...
    ► Copy and Reference Puzzlers Book 2
    Amazon Paperback: amzn.to/3X1LOIx
    Leanpub Ebook: leanpub.com/copyandreferencep...
    ► Copy and Reference Puzzlers Book 3
    Leanpub Ebook: leanpub.com/copyandreferencep...
    ► OpCode Puzzlers Book 1
    Amazon Paperback: amzn.to/3KCNJg6
    Leanpub Ebook: leanpub.com/opcodepuzzlers_book1
    RECOMMENDED BOOKS
    ► Bjarne Stroustrup's A Tour of C++ (now with C++20/23!): amzn.to/3X4Wypr
    AWESOME PROJECTS
    ► The C++ Starter Project - Gets you started with Best Practices Quickly - github.com/cpp-best-practices...
    ► C++ Best Practices Forkable Coding Standards - github.com/cpp-best-practices...
    O'Reilly VIDEOS
    ► Inheritance and Polymorphism in C++ - www.oreilly.com/library/view/...
    ► Learning C++ Best Practices - www.oreilly.com/library/view/...
  • Věda a technologie

Komentáře • 36

  • @sigasigasiga
    @sigasigasiga Před 11 měsíci +16

    4:50 interesting fact: std::for_each returns the callable you've passed in to address this exact problem

  • @emiliancioca
    @emiliancioca Před 11 měsíci +9

    Omg I never thought to use reference_wrapper as a struct member before. That can really help in some niche cases, thanks!

  • @benfrantzdale9231
    @benfrantzdale9231 Před 11 měsíci +3

    I’ve used `std::reference_wrapper` in CTAD so `Foo{std::ref(x)} -> Foo`. It’s nice.

  • @zoso25
    @zoso25 Před 11 měsíci +6

    What's a bit new for me is that we can just randomly declare variables in lambda capture like sum = 0. I usually _captured_ variables from the surrounding scope

  • @Omnifarious0
    @Omnifarious0 Před 11 měsíci +2

    5:38 - I had never thought of that. There's a number of annoying issues that solves well. Thanks!

  • @avramlevitter6150
    @avramlevitter6150 Před 11 měsíci +14

    I've heard just the opposite of "use reference_wrapper as a member" and that you should just use a pointer instead, with the added use of the Guidelines Support Library to wrap it with not_null if it's not allowed to be nullptr to avoid having to constantly confirm its correctness. If you have any thoughts as to why one instead of the other, I'd be interested in it being a video!

    • @cppweekly
      @cppweekly  Před 11 měsíci +3

      Logically, a not_null ptr is a reference, which reference_wrapper can do. But not_null ptr does give you operator->, so that makes some things a little simpler in the use cases.
      I don't have a strongly held opinion here. I just suggest you avoid using raw pointers when you really mean not-null things.

    • @kinershah464
      @kinershah464 Před 9 měsíci

      I just found today that Unreal Engine has something called Shared reference which is non-null shared pointer. Is this related to what you're saying?

  • @Quazgaa
    @Quazgaa Před 11 měsíci +11

    I feel like C++ is 10000x more complicated than it needs to be

  • @MarcoBergamin
    @MarcoBergamin Před 11 měsíci +1

    Informative as usual. Thanks

  • @weekendwarrior3420
    @weekendwarrior3420 Před 11 měsíci

    Great way to start my day.

  • @ohwow2074
    @ohwow2074 Před 11 měsíci +6

    You mentioned many use cases I didn't know about. However you didn't mention the use case with std::thread and std::jthread.

  • @JVApen
    @JVApen Před 11 měsíci +3

    I also use it at places where you call a function taking a reference, such that the caller sees that a ref is being passed: `func(std::ref(inOutArg))`

    • @cppweekly
      @cppweekly  Před 11 měsíci

      Interesting use case. I would be slightly concerned about compile time impact if used everywhere (compiler has to create the std::ref helper function and the std::reference_wrapper class, and the std::reference_wrapper::opreator type function)

    • @unnamed1479
      @unnamed1479 Před 7 měsíci

      @@cppweekly This also intrigues me. As a c++ novice, how hard would it be for the compiler to optimize something like this out? Would it be able to look at the function header and instead emit code as if there was no std::ref call?

  • @acho8387
    @acho8387 Před 11 měsíci

    Thank you.

  • @ishansheth3005
    @ishansheth3005 Před 11 měsíci

    if you use the return value of std::for_each (which is a functor) and use it with argument 0, you dont have to use std::ref. But very good video, i did not know this before about std:: for_each

  • @malcolmrains2426
    @malcolmrains2426 Před 11 měsíci

    amazing!

  • @peterfeatherstone9768
    @peterfeatherstone9768 Před 11 měsíci

    Could you do an episode on coroutines ?

    • @cppweekly
      @cppweekly  Před 11 měsíci

      Cast your vote for that topic idea here: github.com/lefticus/cpp_weekly/issues/

  • @dwarftoad
    @dwarftoad Před 11 měsíci

    Can anyone elaborate on the issue with an object containing a reference member being copied or moved? Could'nt find a previous C++ weekly about it but will keep looking...

    • @cppweekly
      @cppweekly  Před 11 měsíci

      I have the "top places to not use `const`" episode, which touches on the issue. But I may have overstated the problem. I'll have to do some homework on that and do a future episode.

  • @bsdooby
    @bsdooby Před 11 měsíci +1

    the bound method in the example takes by ref, why do I need to add std::ref again for the param? If not done like so, with what is the arg as ref in the bound method "linked" to otherwise?

    • @cppweekly
      @cppweekly  Před 11 měsíci +1

      std::bind *always* copies in the bound arguments, so the "linked"-to value is the one stored in the new object returned by std::bind.

  • @BertLaverman
    @BertLaverman Před 11 měsíci +1

    Library writer: Ok, let's make that a value parameter, references would be weird here. Library user[Dr Evil]: Hah! std::ref! [moves pinky towords upper lip]

  • @Carutsu
    @Carutsu Před 11 měsíci +1

    Why not operator&?

  • @vladigr1
    @vladigr1 Před 11 měsíci

    Why std::move exist, can't we just use the wrapper?

  • @oleksiistri8429
    @oleksiistri8429 Před 11 měsíci +2

    so much unneded crap in c++, but some useful things are completely ignored. for example i searched today a way to handle json objects and did not find, have found only 3rd party solutions. why c++ does not support handling of json, xml, yaml by default, like other languages do, php, javascript, etc?

    • @anon_y_mousse
      @anon_y_mousse Před 11 měsíci +1

      If anyone gives an answer that doesn't boil down to "because committee" I'd be interested in hearing it too. XML has been a standard for so long that one would think every language but C would have a standard library API for it. YAML and JSON on the other hand are more obvious, and super easy to implement in a couple hundred lines of code, if you're not too verbose.

    • @oleksiistri8429
      @oleksiistri8429 Před 11 měsíci

      @@anon_y_mousse if you need only parse/serialize for json, then yeah, but if you need ability to manage json object, insert new values into existing object, or traverse/search through it, and all of this without parse/serialize back and forth, then it becomes not so trivial

    • @oleksiistri8429
      @oleksiistri8429 Před 11 měsíci +1

      @@ClumsyTch and this is bad, this is one of the reasons why c++ loses popularity, no one wants to reinvent the bike

    • @not_ever
      @not_ever Před 11 měsíci

      @@oleksiistri8429 I think you'll find a lot of C++ programmers want to "reinvent the bike", which is why there are about 4 million C++ json parsers out there. I can guarantee if they put a json parser into the standard library, there would still be a significant number of people who write their own.
      nlohmann json or rapidjson are both very good json parser if anyone is interested in json library recommendations.

    • @devluz
      @devluz Před 11 měsíci +3

      See it from another perspective: Most of these parsers that appear to be "built-in" in JavaScript and php are actually just wrappers around existing C/C++ third party libraries that come bundled with these high level languages. For them this was an easy choice: Pick a parser that works best for their use-case. But for C++ which is the base for so many different languages which one would you pick? One advantage of C++ is that it is extremely flexible and customizable. Including entire libraries as default is in conflict with this.
      A json parser for an Arduino, one that runs in the windows or linux kernel, one in user-space on the server and one within a browser will all have very different memory, performance and security considerations! So it will be incredible hard to agree on a default.