c++ - std::move to a function -


i have example code:

#include <iostream>  class struct { public:    struct() { std::cout << "0" << std::endl; }    struct(struct&) { std::cout <<"1"<<std::endl;}    struct(const struct&) { std::cout << "2" << std::endl; } };  class struct2 { public:     struct s;      struct2() {}     void setmember(const struct& aux) { s = aux; } };  int main() {     struct s;     struct2 s2;     s2.setmember(s); } // http://coliru.stacked-crooked.com/a/dd57e8af23f6db4b 

doubt 1:

it printting 2 0, because constructor in main , construct of member of struct2.

the thing is, expecting 3 0, because "setmember" receiving copy of 's', right? happening then?

doubt 2:

i thinking in putting this:

s2.setmember(std::move(s));  

as won't use 's' again, setmember not have '&&' specified, ok? have this? :

s = std::move(aux); 

or main 1 enough?

doubt 3 :

std::vector<a> vectora;  int main() {     a;     // modifies ...     vectora.push_back(std::move(a)); } 

is correct? optimizing moving 'a'? not used anymore , want keep in vector

thanks

because "setmember" receiving copy of 's', right?

well, no. it's receiving const& , copies on assignment operator. since haven't overloaded assignment operator, nothing printed out.


s2.setmember(std::move(s));

this won't solve anything; std::move cast s rvalue, inside of function it's still const&.


rule of thumb: pass-by-value, move out inside:

void setmember(struct aux) { s = std::move(aux); } 

that way "automagically" work; copying lvalues on interface / moving rvalues parameter value, , moving parameter value actual object member.

of course make optimal use of machinery, need rvalue passed there, so...

struct s; struct2 s2; s2.setmember(std::move(s)); 

or perhaps...

s2.setmember(struct()); 

that being said, old code won't break.


as third example, yes, ok, altough i'd probably either

  • move change a function , push_back(function())
  • move changes a as constructor , use emplace_back

Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

php - Find a regex to take part of Email -