c++ - Basic RValue method return -
assuming basic method:
std::string stringtest() { std::string hello_world("testing..."); return std::move(hello_world); }
how should use output:
option a:
auto& string_test_output=stringtest();
option b:
auto string_test_output=stringtest();
is stringtest() temporary value? if so, option not safe. if it's not temporary value, have feeling option b cause copy.
i still getting used rvalue references returning value still scary don't want copying occur or run unnecessary copying!
the best way change method this:
std::string stringtest() { std::string hello_world("testing..."); return hello_world; }
there no need tell function returned object should rvalue, comes automatically value being temporary - is, not bound name @ call site. such, initialized value move-constructed (unless temporary inside function elided entirely), no need manually express such intention.
also, since return type std::string
, return value, not rvalue-reference, there no point moving return argument before returning. in fact, calling std::move
have no effect other possibly tricking compiler perform additional unnecessary move-constructor before returning value. such trick serves no purpose other making code more complex , possibly slower run.
you want return value. 1 reason because of return value optimization (rvo). compilers this, means you're better off returning "copy" gets elided trying clever , returning reference.
even when rvo cannot applied, returning rvalue-reference still not change how returned. when value returned, since temporary @ call site, returned value rvalue can passed along rvalue reference whatever function needs argument. instance, if use return value intialize variable , return value not elided, move constructor still called if available. so, not lost returning value.
given this, should 1 of these catch value:
auto string_test_output = stringtest(); std::string string_test_output = stringtest();
Comments
Post a Comment