c++ - How do you convert a lvalue to an rvalue? And what happens to the `new` lvalue? -
i move object std::vector
using std::vector::push_back()
. seem possible since there std::vector::push_back(value_type&& val)
function. due the existence of std::vector::push_back(value_type const & val)
, copies , overriding call, need convert lvalue object rvalue.
how done?
example:
struct x { int x; x(int x) : x(x) {} }; int main() { std::vector<x> ax; x x(3); ax.push_back(x); // <= want move x in vector ax, not copy. return 0; }
actually, maybe can't be? ask because after writing example, new questions are:
- if move
x
ax
, value ofx.x
? ifx
had explicit destructor, happenx
when leaves scope?
just use std::move()
:
ax.push_back(std::move(x));
concerning question:
if move x ax, value of x.x?
in case, class x
not contain explicitly declared move constructor, compiler generate 1 memberwise move of x
's members. since x
has 1 member of type int
, , moving int
no different copying it, x.x
have same value had before being moved from.
if x had explicit destructor, happen x when leaves scope?
if x
has user-declared destructor, inhibit generation of implicit move constructor - not of implicit copy constructor. therefore, function call:
ax.push_back(std::move(x));
will result in x
being copied ax
. in case, x
destroyed when going out of scope, since has automatic storage duration - no matter whether user-declared destructor present or not.
in general, 1 should not make assumptions on state of object has been moved from, except that state valid (paragraph 17.6.5.15/1 of c++11 standard guarantees case types of standard library).
in concrete, means the functions can safely work object has been moved not have precondition on state of object. typically, 2 such functions destructor , (copy- or move-) assignment operator.
Comments
Post a Comment