When moving a unique_ptr into a lambda, why is it not possible to call reset?Why are Python lambdas useful?What is std::move(), and when should it be used?Why can't I create a vector of lambdas (of the same type) in C++11?How to capture std::unique_ptr “by move” for a lambda in std::for_eachunique_ptr<T> lambda custom deleter for array specializationTrouble move-capturing std::unique_ptr in a lambda using std::bindWhy can I not move unique_ptr from a set to a function argument using an iterator?How to move a unique_ptr?Move objects from a unique_ptr array to a vectorWhy does [=] have a lambda capture?

How to find the version of extensions used on a Joomla website without access to the backend?

Why does this function pointer assignment work when assigned directly but not with the conditional operator?

Did William Shakespeare hide things in his writings?

Possibility to correct pitch from digital versions of records with the hole not centered

Why would "dead languages" be the only languages that spells could be written in?

Howto display unicode character u2026 in terminal mode in emacs

Tiny URL creator

What do I need to see before Spider-Man: Far From Home?

My professor has told me he will be the corresponding author. Will it hurt my future career?

What's the big deal about the Nazgûl losing their horses?

C++ compiler does not check if a method exists in template class

Wearing special clothes in public while in niddah- isn't this a lack of tznius?

Any way to meet code with 40.7% or 40.44% conduit fill?

Why do people prefer metropolitan areas, considering monsters and villains?

How to delete multiple process id of a single process?

Can a USB hub be used to access a drive from two devices?

PhD: When to quit and move on?

Is this car delivery via Ebay Motors on Craigslist a scam?

How do resistors generate different heat if we make the current fixed and changed the voltage and resistance? Notice the flow of charge is constant

Array or vector? Two dimensional array or matrix?

Initializing variables in an "if" statement

What is the maximum amount of diamond in one Minecraft game?

Bringing coumarin-containing liquor into the USA

Does the Milky Way orbit around anything?



When moving a unique_ptr into a lambda, why is it not possible to call reset?


Why are Python lambdas useful?What is std::move(), and when should it be used?Why can't I create a vector of lambdas (of the same type) in C++11?How to capture std::unique_ptr “by move” for a lambda in std::for_eachunique_ptr<T> lambda custom deleter for array specializationTrouble move-capturing std::unique_ptr in a lambda using std::bindWhy can I not move unique_ptr from a set to a function argument using an iterator?How to move a unique_ptr?Move objects from a unique_ptr array to a vectorWhy does [=] have a lambda capture?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








7















When moving std::unique_ptr into the lambda, it is not possible to call reset() on it, because it seems to be const then:



error C2662: void std::unique_ptr<int,std::default_delete<_Ty>>::reset(int *) noexcept': cannot convert 'this' pointer from 'const std::unique_ptr<int,std::default_delete<_Ty>>' to 'std::unique_ptr<int,std::default_delete<_Ty>> &


#include <memory>
int main()

auto u = std::unique_ptr<int>();
auto l = [v = std::move(u)]
v.reset(); // this doesn't compile
;



  1. Why does this happen?

  2. Is it possible to capture the std::unique_ptr in another way which allows calling reset() within the lambda (with C++17 or later)?









share|improve this question






























    7















    When moving std::unique_ptr into the lambda, it is not possible to call reset() on it, because it seems to be const then:



    error C2662: void std::unique_ptr<int,std::default_delete<_Ty>>::reset(int *) noexcept': cannot convert 'this' pointer from 'const std::unique_ptr<int,std::default_delete<_Ty>>' to 'std::unique_ptr<int,std::default_delete<_Ty>> &


    #include <memory>
    int main()

    auto u = std::unique_ptr<int>();
    auto l = [v = std::move(u)]
    v.reset(); // this doesn't compile
    ;



    1. Why does this happen?

    2. Is it possible to capture the std::unique_ptr in another way which allows calling reset() within the lambda (with C++17 or later)?









    share|improve this question


























      7












      7








      7








      When moving std::unique_ptr into the lambda, it is not possible to call reset() on it, because it seems to be const then:



      error C2662: void std::unique_ptr<int,std::default_delete<_Ty>>::reset(int *) noexcept': cannot convert 'this' pointer from 'const std::unique_ptr<int,std::default_delete<_Ty>>' to 'std::unique_ptr<int,std::default_delete<_Ty>> &


      #include <memory>
      int main()

      auto u = std::unique_ptr<int>();
      auto l = [v = std::move(u)]
      v.reset(); // this doesn't compile
      ;



      1. Why does this happen?

      2. Is it possible to capture the std::unique_ptr in another way which allows calling reset() within the lambda (with C++17 or later)?









      share|improve this question
















      When moving std::unique_ptr into the lambda, it is not possible to call reset() on it, because it seems to be const then:



      error C2662: void std::unique_ptr<int,std::default_delete<_Ty>>::reset(int *) noexcept': cannot convert 'this' pointer from 'const std::unique_ptr<int,std::default_delete<_Ty>>' to 'std::unique_ptr<int,std::default_delete<_Ty>> &


      #include <memory>
      int main()

      auto u = std::unique_ptr<int>();
      auto l = [v = std::move(u)]
      v.reset(); // this doesn't compile
      ;



      1. Why does this happen?

      2. Is it possible to capture the std::unique_ptr in another way which allows calling reset() within the lambda (with C++17 or later)?






      c++ c++11 lambda smart-pointers






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 4 hours ago









      Boann

      38.3k13 gold badges92 silver badges123 bronze badges




      38.3k13 gold badges92 silver badges123 bronze badges










      asked 9 hours ago









      Roi DantonRoi Danton

      2,5242 gold badges25 silver badges38 bronze badges




      2,5242 gold badges25 silver badges38 bronze badges






















          4 Answers
          4






          active

          oldest

          votes


















          15















          1. Why does this happen?



          Because the function-call operator of lambda,




          Unless the keyword mutable was used in the lambda-expression, the function-call operator is const-qualified and the objects that were captured by copy are non-modifiable from inside this operator().




          and




          1. Is it possible to capture the std::unique_ptr in another way which allows to call reset() within the lambda



          You need to mark it mutable.




          mutable: allows body to modify the parameters captured by copy, and to call their non-const member functions




          e.g.



          auto l = [v = std::move(u)] mutable 
          v.reset();
          ;





          share|improve this answer
































            5















            1. Why does this happen?



            Because lambdas are by default non-mutable. Therefore all captured objects are const. reset is a non-const member function that modifies the unique pointer.




            1. Is it possible to capture the std::unique_ptr in another way which allows to call reset() within the lambda (with C++17 or later)?



            Yes. Declare the lambda mutable:



            [captures](arguments) mutable body 
            ^^^^^^^


            This is possible since C++11 where lambdas were introduced. All captured non-const objects of a mutable lambda are non-const copies.






            share|improve this answer






























              5














              Within the lambda its data members are immutable by default. You need to append the mutable specifier to the lambda expression.



              As an alternative, you could capture the unique_ptr by reference, as for example:



              #include <memory>

              int main()

              auto u = std::unique_ptr<int>();
              auto l = [&v = u]
              v.reset();
              ;






              share|improve this answer
































                2














                To mutate "member" of the lambda, you need mutable keyword:



                auto l = [v = std::move(u)] () mutable 
                v.reset();
                ;





                share|improve this answer



























                  Your Answer






                  StackExchange.ifUsing("editor", function ()
                  StackExchange.using("externalEditor", function ()
                  StackExchange.using("snippets", function ()
                  StackExchange.snippets.init();
                  );
                  );
                  , "code-snippets");

                  StackExchange.ready(function()
                  var channelOptions =
                  tags: "".split(" "),
                  id: "1"
                  ;
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function()
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled)
                  StackExchange.using("snippets", function()
                  createEditor();
                  );

                  else
                  createEditor();

                  );

                  function createEditor()
                  StackExchange.prepareEditor(
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader:
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  ,
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  );



                  );













                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function ()
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56891083%2fwhen-moving-a-unique-ptr-into-a-lambda-why-is-it-not-possible-to-call-reset%23new-answer', 'question_page');

                  );

                  Post as a guest















                  Required, but never shown

























                  4 Answers
                  4






                  active

                  oldest

                  votes








                  4 Answers
                  4






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  15















                  1. Why does this happen?



                  Because the function-call operator of lambda,




                  Unless the keyword mutable was used in the lambda-expression, the function-call operator is const-qualified and the objects that were captured by copy are non-modifiable from inside this operator().




                  and




                  1. Is it possible to capture the std::unique_ptr in another way which allows to call reset() within the lambda



                  You need to mark it mutable.




                  mutable: allows body to modify the parameters captured by copy, and to call their non-const member functions




                  e.g.



                  auto l = [v = std::move(u)] mutable 
                  v.reset();
                  ;





                  share|improve this answer





























                    15















                    1. Why does this happen?



                    Because the function-call operator of lambda,




                    Unless the keyword mutable was used in the lambda-expression, the function-call operator is const-qualified and the objects that were captured by copy are non-modifiable from inside this operator().




                    and




                    1. Is it possible to capture the std::unique_ptr in another way which allows to call reset() within the lambda



                    You need to mark it mutable.




                    mutable: allows body to modify the parameters captured by copy, and to call their non-const member functions




                    e.g.



                    auto l = [v = std::move(u)] mutable 
                    v.reset();
                    ;





                    share|improve this answer



























                      15












                      15








                      15








                      1. Why does this happen?



                      Because the function-call operator of lambda,




                      Unless the keyword mutable was used in the lambda-expression, the function-call operator is const-qualified and the objects that were captured by copy are non-modifiable from inside this operator().




                      and




                      1. Is it possible to capture the std::unique_ptr in another way which allows to call reset() within the lambda



                      You need to mark it mutable.




                      mutable: allows body to modify the parameters captured by copy, and to call their non-const member functions




                      e.g.



                      auto l = [v = std::move(u)] mutable 
                      v.reset();
                      ;





                      share|improve this answer
















                      1. Why does this happen?



                      Because the function-call operator of lambda,




                      Unless the keyword mutable was used in the lambda-expression, the function-call operator is const-qualified and the objects that were captured by copy are non-modifiable from inside this operator().




                      and




                      1. Is it possible to capture the std::unique_ptr in another way which allows to call reset() within the lambda



                      You need to mark it mutable.




                      mutable: allows body to modify the parameters captured by copy, and to call their non-const member functions




                      e.g.



                      auto l = [v = std::move(u)] mutable 
                      v.reset();
                      ;






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited 9 hours ago

























                      answered 9 hours ago









                      songyuanyaosongyuanyao

                      99.6k11 gold badges195 silver badges263 bronze badges




                      99.6k11 gold badges195 silver badges263 bronze badges























                          5















                          1. Why does this happen?



                          Because lambdas are by default non-mutable. Therefore all captured objects are const. reset is a non-const member function that modifies the unique pointer.




                          1. Is it possible to capture the std::unique_ptr in another way which allows to call reset() within the lambda (with C++17 or later)?



                          Yes. Declare the lambda mutable:



                          [captures](arguments) mutable body 
                          ^^^^^^^


                          This is possible since C++11 where lambdas were introduced. All captured non-const objects of a mutable lambda are non-const copies.






                          share|improve this answer



























                            5















                            1. Why does this happen?



                            Because lambdas are by default non-mutable. Therefore all captured objects are const. reset is a non-const member function that modifies the unique pointer.




                            1. Is it possible to capture the std::unique_ptr in another way which allows to call reset() within the lambda (with C++17 or later)?



                            Yes. Declare the lambda mutable:



                            [captures](arguments) mutable body 
                            ^^^^^^^


                            This is possible since C++11 where lambdas were introduced. All captured non-const objects of a mutable lambda are non-const copies.






                            share|improve this answer

























                              5












                              5








                              5








                              1. Why does this happen?



                              Because lambdas are by default non-mutable. Therefore all captured objects are const. reset is a non-const member function that modifies the unique pointer.




                              1. Is it possible to capture the std::unique_ptr in another way which allows to call reset() within the lambda (with C++17 or later)?



                              Yes. Declare the lambda mutable:



                              [captures](arguments) mutable body 
                              ^^^^^^^


                              This is possible since C++11 where lambdas were introduced. All captured non-const objects of a mutable lambda are non-const copies.






                              share|improve this answer














                              1. Why does this happen?



                              Because lambdas are by default non-mutable. Therefore all captured objects are const. reset is a non-const member function that modifies the unique pointer.




                              1. Is it possible to capture the std::unique_ptr in another way which allows to call reset() within the lambda (with C++17 or later)?



                              Yes. Declare the lambda mutable:



                              [captures](arguments) mutable body 
                              ^^^^^^^


                              This is possible since C++11 where lambdas were introduced. All captured non-const objects of a mutable lambda are non-const copies.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered 9 hours ago









                              eerorikaeerorika

                              97.9k6 gold badges77 silver badges148 bronze badges




                              97.9k6 gold badges77 silver badges148 bronze badges





















                                  5














                                  Within the lambda its data members are immutable by default. You need to append the mutable specifier to the lambda expression.



                                  As an alternative, you could capture the unique_ptr by reference, as for example:



                                  #include <memory>

                                  int main()

                                  auto u = std::unique_ptr<int>();
                                  auto l = [&v = u]
                                  v.reset();
                                  ;






                                  share|improve this answer





























                                    5














                                    Within the lambda its data members are immutable by default. You need to append the mutable specifier to the lambda expression.



                                    As an alternative, you could capture the unique_ptr by reference, as for example:



                                    #include <memory>

                                    int main()

                                    auto u = std::unique_ptr<int>();
                                    auto l = [&v = u]
                                    v.reset();
                                    ;






                                    share|improve this answer



























                                      5












                                      5








                                      5







                                      Within the lambda its data members are immutable by default. You need to append the mutable specifier to the lambda expression.



                                      As an alternative, you could capture the unique_ptr by reference, as for example:



                                      #include <memory>

                                      int main()

                                      auto u = std::unique_ptr<int>();
                                      auto l = [&v = u]
                                      v.reset();
                                      ;






                                      share|improve this answer















                                      Within the lambda its data members are immutable by default. You need to append the mutable specifier to the lambda expression.



                                      As an alternative, you could capture the unique_ptr by reference, as for example:



                                      #include <memory>

                                      int main()

                                      auto u = std::unique_ptr<int>();
                                      auto l = [&v = u]
                                      v.reset();
                                      ;







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited 6 hours ago









                                      Remy Lebeau

                                      354k19 gold badges286 silver badges480 bronze badges




                                      354k19 gold badges286 silver badges480 bronze badges










                                      answered 8 hours ago









                                      Vlad from MoscowVlad from Moscow

                                      144k13 gold badges88 silver badges184 bronze badges




                                      144k13 gold badges88 silver badges184 bronze badges





















                                          2














                                          To mutate "member" of the lambda, you need mutable keyword:



                                          auto l = [v = std::move(u)] () mutable 
                                          v.reset();
                                          ;





                                          share|improve this answer





























                                            2














                                            To mutate "member" of the lambda, you need mutable keyword:



                                            auto l = [v = std::move(u)] () mutable 
                                            v.reset();
                                            ;





                                            share|improve this answer



























                                              2












                                              2








                                              2







                                              To mutate "member" of the lambda, you need mutable keyword:



                                              auto l = [v = std::move(u)] () mutable 
                                              v.reset();
                                              ;





                                              share|improve this answer















                                              To mutate "member" of the lambda, you need mutable keyword:



                                              auto l = [v = std::move(u)] () mutable 
                                              v.reset();
                                              ;






                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited 9 hours ago

























                                              answered 9 hours ago









                                              Jarod42Jarod42

                                              125k12 gold badges109 silver badges196 bronze badges




                                              125k12 gold badges109 silver badges196 bronze badges



























                                                  draft saved

                                                  draft discarded
















































                                                  Thanks for contributing an answer to Stack Overflow!


                                                  • Please be sure to answer the question. Provide details and share your research!

                                                  But avoid


                                                  • Asking for help, clarification, or responding to other answers.

                                                  • Making statements based on opinion; back them up with references or personal experience.

                                                  To learn more, see our tips on writing great answers.




                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function ()
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56891083%2fwhen-moving-a-unique-ptr-into-a-lambda-why-is-it-not-possible-to-call-reset%23new-answer', 'question_page');

                                                  );

                                                  Post as a guest















                                                  Required, but never shown





















































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown

































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown







                                                  Popular posts from this blog

                                                  Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                                                  Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                                                  Ласкавець круглолистий Зміст Опис | Поширення | Галерея | Примітки | Посилання | Навігаційне меню58171138361-22960890446Bupleurum rotundifoliumEuro+Med PlantbasePlants of the World Online — Kew ScienceGermplasm Resources Information Network (GRIN)Ласкавецькн. VI : Літери Ком — Левиправивши або дописавши її