c++11 - C++ 11 - Is moving non local variable safe? -


this question has answer here:

say have function goes like:

void a_fct( std::vector<double> &some_vector ) {   std::vector<double> a_temporary_vector = some_vector;    ... stuff involving a_temporary_vector ...    some_vector = a_temporary_vector; } 

which of course bit silly, intended bringing following general questions:

  • it seems me 1 should rather move a_temporary_vector some_vector here, goes out of scope. safe move some_vector a_temporary_vector rather copying ?

  • imagine somewhere else in code, have pointer vector given argument here. pointer still pointing if move some_vector a_temporary_vector ?

in both cases, can expect true stl implementation ?

the standard (in 17.6.5.15) says:

objects of types defined in c++ standard library may moved (12.8). move operations may explicitly specified or implicitly generated. unless otherwise specified, such moved-from objects shall placed in valid unspecified state.

thus, some_vector required have (unspecified but) valid state after being moved from. you're allowed move temporary , move again temporary some_vector.

std::vector<double> a_temporary_vector = std::move(some_vector); // stuff on a_temporary_vector not some_vector some_vector = std::move(a_temporary_vector); 

pointers , references some_vector still valid pointers or references content of some_vector not (as expect when passing object function taking non-constant reference).

note: use swap in case instead if you're not sure whether move or not.

void foo( std::vector<double> &some_vector ) {   // swap contents of some_vector temporary   std::vector<double> a_temporary_vector;   a_temporary_vector.swap(some_vector);    // operate on temporary    // swap content some_vector   a_temporary_vector.swap(some_vector);   some_vector = a_temporary_vector; } 

Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -