C++ Weekly - Ep 126 - Lambdas With Destructors

Поділитися
Вставка
  • Опубліковано 28 лип 2024
  • ☟☟ Awesome T-Shirts! Sponsors! Books! ☟☟
    Upcoming Workshop: C++ Best Practices, NDC TechTown, Sept 9-10, 2024
    ► ndctechtown.com/workshops/c-b...
    Upcoming Workshop: Applied constexpr: The Power of Compile-Time Resources, C++ Under The Sea, October 10, 2024
    ► cppunderthesea.nl/workshops/
    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/...
    ChaiScript: chaiscript.com
    Music: www.bensound.com/royalty-free...
  • Наука та технологія

КОМЕНТАРІ • 43

  • @superscatboy
    @superscatboy 3 роки тому +27

    C++ Weekly, 2029: "Concrete types deprecated, everything is a lambda now"

  • @devluz
    @devluz 6 років тому +74

    Might come in handy if we ever have a "most ugly C++" competition

  • @vertigo6982
    @vertigo6982 6 років тому +11

    One can never have too many videos about lambdas. I'm really enjoying every one of them.

  • @applicative_functor
    @applicative_functor 6 років тому +27

    Lambda, which capture another lambda inline, which have structure declaration and usage. I was struck to the core of my soul by the fact that it is possible at all !
    Is it possible to unsee this?! :D Why not add few levels of nesting templates, make them mutable, and mix with SFINAE, type-traits and move-semantics? :D

  • @goshisanniichi
    @goshisanniichi 4 роки тому +1

    I could see it used for timing, something like function profiling. It's not that necessary anymore, but you have the lambda grab a mutex on creation and then release it on destruction, that way you don't have to worry about things like mutexes not being release in the even exceptions and things like that.

  • @NonTwinBrothers
    @NonTwinBrothers 9 місяців тому

    I had to find this video again just to convince myself it wasn't a dream

  • @emiliadaria
    @emiliadaria 6 років тому +2

    I am amazed

  • @rabbitdrink
    @rabbitdrink 4 роки тому +2

    if i were to use something like that id most likely just put together a struct with operator() or use a finally object from some utility library

  • @KobiCohenArazi
    @KobiCohenArazi 6 років тому

    Nice! didn't think about it...

  • @zackyezek3760
    @zackyezek3760 15 днів тому

    Or you can just write a regular, old school functor struct directly and bypass both the unnecessary extra wrapping layers AND the write only lambda code.
    You can still do things with those that no lambda can, like a recursive calls. And in this case it’d be faster too.

  • @ukaszdrozdz6200
    @ukaszdrozdz6200 6 років тому +8

    This looks like it could have a use in a SCOPE_EXIT{ } implementation.

    • @headlibrarian1996
      @headlibrarian1996 6 років тому

      I like std::unique_ptr with a custom destruction function for that.

    • @ukaszdrozdz6200
      @ukaszdrozdz6200 6 років тому

      std::unique_ptr just for a SCOPE_EXIT? What for? It's just a wasteful heap allocation ;)

    • @headlibrarian1996
      @headlibrarian1996 6 років тому +13

      Łukasz Drożdż No heap allocation. std::unique_ptr has a two argument constructor: a pointer to manage and a custom deleter function. Pass in nullptr and the function (which ignores the nullptr argument). Voila!

  • @AxelStrem
    @AxelStrem 6 років тому +1

    If I ever happen to have a container of mutexes, I'll make sure to use a "destructor lambda" with std::for_each to lock them all :D

  • @DusanJovanovicDBJ
    @DusanJovanovicDBJ 3 роки тому +2

    That lambda has no destructor. That struct S has a destructor.

    • @pdgiddie
      @pdgiddie Рік тому

      The destructor is called when the lambda goes out of scope, so 🤷

  • @danielrhouck
    @danielrhouck 6 років тому +2

    Wouldn't a simpler lambda with a destruction be [s=std::string("Hello")](){}?

    • @connorhorman
      @connorhorman 5 років тому

      Daniel Houck Even simpler [s=“Hello”s]{}

  • @alexeiz
    @alexeiz 6 років тому +6

    Why do these kind of programming technics remind me Javascript?

  • @cmdlp4178
    @cmdlp4178 6 років тому +1

    I think it can be useful for debugging and optimizing. When I write functions taking a lambda function as a parameter, I always pass them by value, because in most cases the lambdas just capture a reference to all variables, this should be as fast as copying a pointer, but when other people use the functions, they might capture variables by value, this could help me to improve the code, so that lambdas are not copied all over the place.
    But do you think it is better to pass lambdas by value, by l-value reference or universal reference when writing functions like in the -header?

    • @N00byEdge
      @N00byEdge 6 років тому +1

      Imo, universal reference, the caller probably knows best what the lambda is doing

    • @cmdlp4178
      @cmdlp4178 6 років тому

      N00byEdge I think, when you need to write code for yourself fast, you can use pass-by-value, and do not need to type two characters(&&), as long as the lambda just has a reference to all locals. But when others may use it, you should use universal references. However, you should also use std::forward, when the lambda is used once, this could lead to more boilerplate code. On the other hand, when a lambda is called, there is no difference, if it is called as an lvalue or rvalue, but for user-types there may be overloads to operator(), which do the most optimized thing if the callable object is lvalue or rvalue.
      // this object returns a string-object when called, it could also be a reference, but this directly shows the point
      struct get_string {
      std::string str;
      std::string operator()() const {
      return str; // copy
      };
      std::string operator()() && {
      return std::move(str); // move
      };
      };
      template
      auto create_1(t_Func&& f) {
      return std::make_tuple(
      std::forward(f())
      );
      };
      template
      auto create_2(t_Func&& f) {
      return std::tuple_concat(
      create_1(f), // lvalue, used again later
      create_2(std::forward(f))
      );
      };
      conclusion: In the most cases use universal references. And use std::forward, when you know, it is not used again. -- Exactly as you would do with other object types.

  • @X_Baron
    @X_Baron 5 років тому +2

    I'm puzzled by that struct S being in scope after the outer lambda.

  • @alexmanea4920
    @alexmanea4920 6 років тому +1

    This is perfect for lambda-enabled command pattern

    • @alexmanea4920
      @alexmanea4920 6 років тому +2

      I _command_ to you lord ! Consider it done

  • @foomoo1088
    @foomoo1088 Рік тому

    Not sure this is really a “destructor” for the lambda … it gets called twice . Also not clear why you’d need it

    • @cppweekly
      @cppweekly  Рік тому +2

      Destructor is only called once per object. In this example there are two different lambdas created. The original, and a copy. Each must have its destructor called. In this regard lambdas are no different than any other object in C++

  • @markusbock3364
    @markusbock3364 6 років тому

    I usually use a class that is construct able with a std::function only to make a scope guard for when using a c api that requires cleanup. Or if possible I use boost scope exit

    • @markusbock3364
      @markusbock3364 6 років тому

      Red0x Because this kind of usage was the first thing that came to my mind when he asked for scenarios that this might be useful in

    • @ruadeil_zabelin
      @ruadeil_zabelin 6 років тому +4

      If you have a C object that requires cleanup, you can pack it in a unique_ptr with a custom cleanup:
      std::unique_ptr object(create_someobject_in_c(), cleanup_someobject_in_c);
      This will give you all the freedom and protection you need for C stuff that requires cleanup. Indeed boost scope_exit also works, but this is better if you need to keep it as a class member or whatever.

    • @markusbock3364
      @markusbock3364 6 років тому +1

      Kayak Fan Nice never thought of that thank you!

  • @shushens
    @shushens 6 років тому +7

    I find the name misleading, because the destructor does not destroy the lambda.

  • @xavierthomas1980
    @xavierthomas1980 6 років тому

    I "common" use case would be capturing a object with a destructor by value.

  • @schekla
    @schekla 6 років тому +1

    WOW! So much boilerplate. Why not just use a class?

  • @MatkatMusic
    @MatkatMusic 5 років тому +5

    i think you deserve to be fired if you ever write code like what was presented in this video on a team project. this is unmaintainable code and is complex for the sake of being complex with no useful gain.

  • @cybermindable
    @cybermindable 6 років тому +5

    Наркоман что ли?