Re: A question on "uncopyable" that disable copy constructor
=E5=9C=A8 2012=E5=B9=B42=E6=9C=8826=E6=97=A5=E6=98=9F=E6=9C=9F=E6=97=A5UTC+=
8=E4=B8=8A=E5=8D=883=E6=97=B610=E5=88=8608=E7=A7'=EF=BC=8CJuha Nieminen=
=E5=86=99=E9=81=93=EF=BC=9A
bartek szurgot <basz@no.spam> wrote:
std::vector<Movable> v;
Movable m;
v.push_back(m); // error - cannot copy
v.push_back( std::move(m) ); // ok - moves object
I'm not so sure doing that is such a good "pattern" because after
giving 'm' to the vector you are left with an "empty"/"null" 'm' which
has nothing in it (because what it had was moved to the vector).
A more sensible "pattern" would be to create a temporary that gets
destroyed immediately after its contents have been moved to the vector,
that is:
v.push_back(Movable());
OTOH, there might be some situations where you need to do it like your
version, for example like:
Movable m;
m.doSomething(abc);
m.doSomethingElse(def);
v.push_back(std::move(m));
However, in this case it might be worthy of consideration to move such
initialization to a function, so you would have something like:
Movable gimmeAMovable()
{
Movable m;
m.doSomething(abc);
m.doSomethingElse(def);
return m;
}
...
v.push_back(gimmeAMovable());
This way you don't end up with an "empty" object from which content has
been moved away.
=E5=9C=A8 2012=E5=B9=B42=E6=9C=8826=E6=97=A5=E6=98=9F=E6=9C=9F=E6=97=A5UTC+=
8=E4=B8=8A=E5=8D=883=E6=97=B610=E5=88=8608=E7=A7'=EF=BC=8CJuha Nieminen=
=E5=86=99=E9=81=93=EF=BC=9A
bartek szurgot <basz@no.spam> wrote:
std::vector<Movable> v;
Movable m;
v.push_back(m); // error - cannot copy
v.push_back( std::move(m) ); // ok - moves object
I'm not so sure doing that is such a good "pattern" because after
giving 'm' to the vector you are left with an "empty"/"null" 'm' which
has nothing in it (because what it had was moved to the vector).
A more sensible "pattern" would be to create a temporary that gets
destroyed immediately after its contents have been moved to the vector,
that is:
v.push_back(Movable());
OTOH, there might be some situations where you need to do it like your
version, for example like:
Movable m;
m.doSomething(abc);
m.doSomethingElse(def);
v.push_back(std::move(m));
I think here the index of the moved m in v should be saved in the next l=
ine. But it is possible that the vector v is used as a stack of the same t=
ype of objects.