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_vectorsome_vectorhere, goes out of scope. safe movesome_vectora_temporary_vectorrather copying ?imagine somewhere else in code, have pointer vector given argument here. pointer still pointing if move
some_vectora_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
Post a Comment