#Unique ptrs and vectors

21 messages · Page 1 of 1 (latest)

latent ravine
#

I understand that I can’t just push back a unique ptr ie. myVec.push_back(uPtr); because it doesn’t support copying but I’d need to use std::move to transfer ownership. Why is it that myVec.push_back(make_unique<…>()); works then? Wouldn’t it just make a copy aswell,. Which wouldn’t work

lusty marlinBOT
#

When your question is answered use !solved or the button below to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

tawdry grail
latent ravine
tawdry grail
#

kinda confused at the question. what do you think std::move() does?

latent ravine
#

It moves instead of copying

#

That’s like all I know lol

#

So for like unique ptrs you can’t copy so you can’t directly pass a unique ptr to be pushed on to a vector because it will try to copy it

#

But you can std::move the pointer so that ownership is transferred

#

So I’m confused on why you can literally pass what is returned by make_unique

dreamy yew
#

std::move isn't the only thing that moves

#

In general, temporary objects are moved automatically (or more accurately, rvalues are moved automatically, and std::move is just a cast to an rvalue)

#

std::move is a kludge that you use when the compiler can't guess that you want to move, which happens when the source isn't an rvalue

latent ravine
#

I see

#

I guess I’m just confused on an r value now

#

What specific is an r value? Because I just know that it evaluates to a value compared to an l value with evaluates to an object

#

Also l values can be in place of r values right, so that’s what confuses me in this context

dreamy yew
#

Being an rvalue/lvalue is a property of an expression

#

Rvalue means that this expression probably refers to a temporary object. Which isn't always true, e.g. std::move can force an rvalue to refer to something else

dreamy yew