c++ - Creating an object, local variable vs rvalue reference -


is there advantage using r value reference when create object, otherwise in normal local variable?

foo&& cn = foo(); cn.m_flag = 1; bar.m_foo = std::move(cn); //cn not used again  foo cn; cn.m_flag = 1; bar.m_foo = std::move(cn); //is ok move non rvalue reference? //cn not used again 

in first code snippet, seems clear there not copies, i'd guess in second compile optimize copies out?

also in first snippet, object stored in memory (in second stored in stack frame of enclosing function)?

those code fragments equivalent. this:

foo&& rf = foo(); 

is binding temporary reference, extends lifetime of temporary of reference. foo destroyed when rf goes out of scope. same behavior with:

foo f; 

with exception in latter example f default-initialized in former example rf value-initialized. types, 2 equivalent. others, not. if had instead written foo f{}, difference goes away.

one remaining difference pertains copy elision:

foo give_a_foo_rv() {     foo&& rf = foo();     return rf; }  foo give_a_foo() {     foo f{};     return f; } 

rvo not allowed performed in first example, because rf not have same type return type of give_a_foo_rv(). moreover, rf won't automatically moved return type because it's not object doesn't have automatic storage duration, that's copy:

foo f = give_a_foo_rv(); // copy happens here! foo g = give_a_foo();    // no move or copy 

it seems clear there not copies

that depends entirely on moving foo does. if foo looks like:

struct foo {     foo() = default;     foo(foo const& ) = default;     foo& operator=(foo const& ) = default;      // members }; 

then moving foo still copying.


and yes, okay std::move(f) in second example. don't need object of type rvalue reference t move it. severely limit usefulness of moving.


Comments

Popular posts from this blog

serialization - Convert Any type in scala to Array[Byte] and back -

matplotlib support failed in PyCharm on OSX -

python - Matplotlib: TypeError: 'AxesSubplot' object is not callable -