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;
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
add a comment |
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
add a comment |
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
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
c++ smart-pointers stdvector move-semantics
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
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
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.
add a comment |
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.
add a comment |
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.
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
add a comment |
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.
add a comment |
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.
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.
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
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered 9 hours ago
Remy LebeauRemy Lebeau
354k19 gold badges286 silver badges480 bronze badges
354k19 gold badges286 silver badges480 bronze badges
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
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
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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