Compiler doesn't fail when pushing back a std::unique_ptr into a std::vectorConcatenating two std::vectorsHow to find out if an item is present in a std::vector?What is std::move(), and when should it be used?std::auto_ptr to std::unique_ptrHow to store a vector of objects of an abstract class which are given by std::unique_ptr?C++ std::unique_ptr but non movable?Move objects from a unique_ptr array to a vectorVector push_back error when compilingpush_back vs emplace_back to a std::vector<std::string>Move std::unique_ptr<int[]> to Platform::Collections::Vector<int>

Bold and Colored Image Caption

Did depressed people far more accurately estimate how many monsters they killed in a video game?

Can a landlord force all residents to use the landlord's in-house debit card accounts?

How to properly translate the key phrase of Erdoğan's 2016 letter to Putin, "kusura bakmasınlar," to Russian

What would +1/+2/+3 items be called in game?

Why does Trump want a citizenship question on the census?

Hail hit my roof. Do I need to replace it?

Why is a mixture of two normally distributed variables only bimodal if their means differ by at least two times the common standard deviation?

Found and corrected a mistake on someone's else paper -- praxis?

Compiler doesn't fail when pushing back a std::unique_ptr into a std::vector

How does the Melf's Minute Meteors spell interact with the Evocation wizard's Sculpt Spells feature?

Why does the Antonov AN-225 not have any winglets?

How do you move up one folder in Finder?

How do I explain that I don't want to maintain old projects?

What are the effects of abstaining from eating a certain flavor?

If props is missing Should I use memo?

Intern not wearing safety equipment; how could I have handled this differently?

Users forgetting to regenerate PDF before sending it

What does the multimeter dial do internally?

Is there a way I can open the Windows 10 Ubuntu bash without running the ~/.bashrc script?

Is it okay to use open source code to do an interview task?

When did "&" stop being taught alongside the alphabet?

A Logic Puzzle—One of These Things Doesn’t Quite Fit

Swapping "Good" and "Bad"



Compiler doesn't fail when pushing back a std::unique_ptr into a std::vector


Concatenating two std::vectorsHow to find out if an item is present in a std::vector?What is std::move(), and when should it be used?std::auto_ptr to std::unique_ptrHow to store a vector of objects of an abstract class which are given by std::unique_ptr?C++ std::unique_ptr but non movable?Move objects from a unique_ptr array to a vectorVector push_back error when compilingpush_back vs emplace_back to a std::vector<std::string>Move std::unique_ptr<int[]> to Platform::Collections::Vector<int>






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








6















An unique_ptr cannot be pushed back into a std::vector since it is non-copyable, unless std::move is used. However, let be F a function that returns an unique_ptr, then, the operation std::vector::push_back(F()) is allowed. There is an example below:



#include <iostream>
#include <vector>
#include <memory>

class A
public:
int f() return _f + 10;

private:
int _f = 20;
;

std::unique_ptr<A> create() return std::unique_ptr<A>(new A);


int main()
std::unique_ptr<A> p1(new A());

std::vector< std::unique_ptr<A> > v;

v.push_back(p1); // (1) This fails, should use std::move

v.push_back(create()); // (2) This doesn't fail, should use std::move?

return 0;



(2) is allowed, but (1) is not. Is this because the returned value is moved somehow implicitly?



In (2), is it actually necessary to use std::move?










share|improve this question






























    6















    An unique_ptr cannot be pushed back into a std::vector since it is non-copyable, unless std::move is used. However, let be F a function that returns an unique_ptr, then, the operation std::vector::push_back(F()) is allowed. There is an example below:



    #include <iostream>
    #include <vector>
    #include <memory>

    class A
    public:
    int f() return _f + 10;

    private:
    int _f = 20;
    ;

    std::unique_ptr<A> create() return std::unique_ptr<A>(new A);


    int main()
    std::unique_ptr<A> p1(new A());

    std::vector< std::unique_ptr<A> > v;

    v.push_back(p1); // (1) This fails, should use std::move

    v.push_back(create()); // (2) This doesn't fail, should use std::move?

    return 0;



    (2) is allowed, but (1) is not. Is this because the returned value is moved somehow implicitly?



    In (2), is it actually necessary to use std::move?










    share|improve this question


























      6












      6








      6








      An unique_ptr cannot be pushed back into a std::vector since it is non-copyable, unless std::move is used. However, let be F a function that returns an unique_ptr, then, the operation std::vector::push_back(F()) is allowed. There is an example below:



      #include <iostream>
      #include <vector>
      #include <memory>

      class A
      public:
      int f() return _f + 10;

      private:
      int _f = 20;
      ;

      std::unique_ptr<A> create() return std::unique_ptr<A>(new A);


      int main()
      std::unique_ptr<A> p1(new A());

      std::vector< std::unique_ptr<A> > v;

      v.push_back(p1); // (1) This fails, should use std::move

      v.push_back(create()); // (2) This doesn't fail, should use std::move?

      return 0;



      (2) is allowed, but (1) is not. Is this because the returned value is moved somehow implicitly?



      In (2), is it actually necessary to use std::move?










      share|improve this question
















      An unique_ptr cannot be pushed back into a std::vector since it is non-copyable, unless std::move is used. However, let be F a function that returns an unique_ptr, then, the operation std::vector::push_back(F()) is allowed. There is an example below:



      #include <iostream>
      #include <vector>
      #include <memory>

      class A
      public:
      int f() return _f + 10;

      private:
      int _f = 20;
      ;

      std::unique_ptr<A> create() return std::unique_ptr<A>(new A);


      int main()
      std::unique_ptr<A> p1(new A());

      std::vector< std::unique_ptr<A> > v;

      v.push_back(p1); // (1) This fails, should use std::move

      v.push_back(create()); // (2) This doesn't fail, should use std::move?

      return 0;



      (2) is allowed, but (1) is not. Is this because the returned value is moved somehow implicitly?



      In (2), is it actually necessary to use std::move?







      c++ smart-pointers stdvector move-semantics






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 9 hours ago









      0x499602D2

      70.2k29 gold badges124 silver badges211 bronze badges




      70.2k29 gold badges124 silver badges211 bronze badges










      asked 9 hours ago









      DanDan

      8287 silver badges21 bronze badges




      8287 silver badges21 bronze badges






















          3 Answers
          3






          active

          oldest

          votes


















          11














          std::move(X) essentially means "here, treat X as if it was a temporary object".



          create() returns a temporary std::unique_ptr<A> to begin with, so move is unnecessary.




          If you want to know more, look into the value categories. Your compiler uses value categories to determine if an expression refers to a temporary object ("rvalue") or not ("lvalue").



          p1 is an lvalue, and create() is an rvalue.






          share|improve this answer
































            2














            std::vector::push_back() has an overload that takes an rvalue reference as input:



            void push_back( T&& value );


            The return value of create() is an unnamed temporary, ie an rvalue, so it can be passed as-is to push_back() without needing to use std::move() on it.



            std::move() is needed only when passing a named variable, ie an lvalue, where an rvalue is expected.






            share|improve this answer






























              2














              With C++11 we got move constructors and rvalues semantics.



              std::move(X) is just a cast to a rvalue which converts X to X&& that is it. Than move ctor takes the job over and move constructors typically "steal" the resources held by the argument. unique_ptr have a move ctor.



              Function return values are already a rvalue(unless the function returns an lvalue reference as indicated by @HolyBlackCat in comments) which will trigger the move ctor without needing any extra cast. And since move ctor is defined for unique_ptr it will compile.



              Also the reason why v.push_back(p1);failing is: you try to call copy constructor with an lvalue and it fails because unique_ptr does not have a copy ctor.






              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%2f56925919%2fcompiler-doesnt-fail-when-pushing-back-a-stdunique-ptr-into-a-stdvector%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                11














                std::move(X) essentially means "here, treat X as if it was a temporary object".



                create() returns a temporary std::unique_ptr<A> to begin with, so move is unnecessary.




                If you want to know more, look into the value categories. Your compiler uses value categories to determine if an expression refers to a temporary object ("rvalue") or not ("lvalue").



                p1 is an lvalue, and create() is an rvalue.






                share|improve this answer





























                  11














                  std::move(X) essentially means "here, treat X as if it was a temporary object".



                  create() returns a temporary std::unique_ptr<A> to begin with, so move is unnecessary.




                  If you want to know more, look into the value categories. Your compiler uses value categories to determine if an expression refers to a temporary object ("rvalue") or not ("lvalue").



                  p1 is an lvalue, and create() is an rvalue.






                  share|improve this answer



























                    11












                    11








                    11







                    std::move(X) essentially means "here, treat X as if it was a temporary object".



                    create() returns a temporary std::unique_ptr<A> to begin with, so move is unnecessary.




                    If you want to know more, look into the value categories. Your compiler uses value categories to determine if an expression refers to a temporary object ("rvalue") or not ("lvalue").



                    p1 is an lvalue, and create() is an rvalue.






                    share|improve this answer















                    std::move(X) essentially means "here, treat X as if it was a temporary object".



                    create() returns a temporary std::unique_ptr<A> to begin with, so move is unnecessary.




                    If you want to know more, look into the value categories. Your compiler uses value categories to determine if an expression refers to a temporary object ("rvalue") or not ("lvalue").



                    p1 is an lvalue, and create() is an rvalue.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited 9 hours ago

























                    answered 9 hours ago









                    HolyBlackCatHolyBlackCat

                    19.4k4 gold badges40 silver badges73 bronze badges




                    19.4k4 gold badges40 silver badges73 bronze badges























                        2














                        std::vector::push_back() has an overload that takes an rvalue reference as input:



                        void push_back( T&& value );


                        The return value of create() is an unnamed temporary, ie an rvalue, so it can be passed as-is to push_back() without needing to use std::move() on it.



                        std::move() is needed only when passing a named variable, ie an lvalue, where an rvalue is expected.






                        share|improve this answer



























                          2














                          std::vector::push_back() has an overload that takes an rvalue reference as input:



                          void push_back( T&& value );


                          The return value of create() is an unnamed temporary, ie an rvalue, so it can be passed as-is to push_back() without needing to use std::move() on it.



                          std::move() is needed only when passing a named variable, ie an lvalue, where an rvalue is expected.






                          share|improve this answer

























                            2












                            2








                            2







                            std::vector::push_back() has an overload that takes an rvalue reference as input:



                            void push_back( T&& value );


                            The return value of create() is an unnamed temporary, ie an rvalue, so it can be passed as-is to push_back() without needing to use std::move() on it.



                            std::move() is needed only when passing a named variable, ie an lvalue, where an rvalue is expected.






                            share|improve this answer













                            std::vector::push_back() has an overload that takes an rvalue reference as input:



                            void push_back( T&& value );


                            The return value of create() is an unnamed temporary, ie an rvalue, so it can be passed as-is to push_back() without needing to use std::move() on it.



                            std::move() is needed only when passing a named variable, ie an lvalue, where an rvalue is expected.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 9 hours ago









                            Remy LebeauRemy Lebeau

                            354k19 gold badges286 silver badges480 bronze badges




                            354k19 gold badges286 silver badges480 bronze badges





















                                2














                                With C++11 we got move constructors and rvalues semantics.



                                std::move(X) is just a cast to a rvalue which converts X to X&& that is it. Than move ctor takes the job over and move constructors typically "steal" the resources held by the argument. unique_ptr have a move ctor.



                                Function return values are already a rvalue(unless the function returns an lvalue reference as indicated by @HolyBlackCat in comments) which will trigger the move ctor without needing any extra cast. And since move ctor is defined for unique_ptr it will compile.



                                Also the reason why v.push_back(p1);failing is: you try to call copy constructor with an lvalue and it fails because unique_ptr does not have a copy ctor.






                                share|improve this answer





























                                  2














                                  With C++11 we got move constructors and rvalues semantics.



                                  std::move(X) is just a cast to a rvalue which converts X to X&& that is it. Than move ctor takes the job over and move constructors typically "steal" the resources held by the argument. unique_ptr have a move ctor.



                                  Function return values are already a rvalue(unless the function returns an lvalue reference as indicated by @HolyBlackCat in comments) which will trigger the move ctor without needing any extra cast. And since move ctor is defined for unique_ptr it will compile.



                                  Also the reason why v.push_back(p1);failing is: you try to call copy constructor with an lvalue and it fails because unique_ptr does not have a copy ctor.






                                  share|improve this answer



























                                    2












                                    2








                                    2







                                    With C++11 we got move constructors and rvalues semantics.



                                    std::move(X) is just a cast to a rvalue which converts X to X&& that is it. Than move ctor takes the job over and move constructors typically "steal" the resources held by the argument. unique_ptr have a move ctor.



                                    Function return values are already a rvalue(unless the function returns an lvalue reference as indicated by @HolyBlackCat in comments) which will trigger the move ctor without needing any extra cast. And since move ctor is defined for unique_ptr it will compile.



                                    Also the reason why v.push_back(p1);failing is: you try to call copy constructor with an lvalue and it fails because unique_ptr does not have a copy ctor.






                                    share|improve this answer















                                    With C++11 we got move constructors and rvalues semantics.



                                    std::move(X) is just a cast to a rvalue which converts X to X&& that is it. Than move ctor takes the job over and move constructors typically "steal" the resources held by the argument. unique_ptr have a move ctor.



                                    Function return values are already a rvalue(unless the function returns an lvalue reference as indicated by @HolyBlackCat in comments) which will trigger the move ctor without needing any extra cast. And since move ctor is defined for unique_ptr it will compile.



                                    Also the reason why v.push_back(p1);failing is: you try to call copy constructor with an lvalue and it fails because unique_ptr does not have a copy ctor.







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited 8 hours ago

























                                    answered 9 hours ago









                                    Kadir Erdem DemirKadir Erdem Demir

                                    2,2972 gold badges20 silver badges32 bronze badges




                                    2,2972 gold badges20 silver badges32 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%2f56925919%2fcompiler-doesnt-fail-when-pushing-back-a-stdunique-ptr-into-a-stdvector%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

                                        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

                                        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

                                        199年 目錄 大件事 到箇年出世嗰人 到箇年死嗰人 節慶、風俗習慣 導覽選單