lundi 24 août 2015

Lifetime of rvalue ref

The code below works fine and as far as I understand every time the function is called, a local variable (i.e. vector) will be created and the ownership will be transferred in a rvalue reference at first call and in a const reference (if I remove it won't even compile) at second call. As a result, the local variables didn't actually die when the function terminated, but when the references in main went out of scope (i.e. in the 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 i = 0; i < rval_ref.size(); ++i)
        std::cout << rval_ref[i] << "\n";

    const std::vector<int> &con_ref = get_v();

    for(unsigned int i = 0; i < 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 I thought local variables die when they got out of scope, except if a static keyword precedes them, or they have been dynamically allocated, or even get copied. In this case, the vector is not copied. Maybe my C background keeps me back from understand the concept here. Can you help me please?

As a sidenote, the first case lets you modify the vector, while the second obviously won't. Guess the first is a C++11 feature, while the second is the traditional one.


I just made an example with a custom class and the copy constructor won't be called, but it will work as the example above!

Aucun commentaire:

Enregistrer un commentaire