c++ - Lifetime of rvalue ref -
the code below works fine , far understand every time function called, local variable (i.e. vector) created , ownership transferred in rvalue reference @ first call , in const reference (if remove won't compile) @ second call. result, local variables didn't die when function terminated, when references in main went out of scope (i.e. in end of main()
), i think!
#include <iostream> #include <vector> std::vector<int> get_v(void) { std::vector<int> v{1,2,3}; return v; } int main() { std::vector<int> &&rval_ref = get_v(); for(unsigned int = 0; < rval_ref.size(); ++i) std::cout << rval_ref[i] << "\n"; const std::vector<int> &con_ref = get_v(); for(unsigned int = 0; < con_ref.size(); ++i) std::cout << con_ref[i] << "\n"; return 0; }
output:
gsamaras@pythagoras:~$ g++ -std=c++0x -wall px.cpp gsamaras@pythagoras:~$ ./a.out 1 2 3 1 2 3
but thought local variables die when got out of scope, except if static
keyword precedes them, or have been dynamically allocated, or copied. in case, vector not copied. maybe c background keeps me understand concept here. can me please?
as sidenote, first case lets modify vector, while second won't. guess first c++11 feature, while second traditional one.
i made example custom class , copy constructor won't called, work example above!
when write std::vector<int> &&rval_ref = get_v();
these conceptual steps when return v;
reached
- a temporary object, called return value created. object initialized if
std::vector<int> x{v};
. "lives" inmain
, naturally "go out of scope" when statement inmain
has finished. v
destroyed- the reference
rval_ref
bound temporary object. binding reference temporary object causes object have lifetime extended match reference's lifetime.
the name "temporary object" bit of misnomer since object may last quite long time, nevertheless official name. "unnamed object" possible description.
your references not refer v
, refer copy of (since function returns value). though v
destroyed, copy not destroyed.
your test code did not show copy-constructor call (step 1 above) because of copy elision. copy elision means compiler may choose use same memory space v
have used return value; , omit destructor v
, copy-constructor return value (even if functions had side-effects).
Comments
Post a Comment