vendredi 24 février 2017

Lifetime extension, prvalues and xvalues

Following the well accepted answer to this question Do rvalue references allow dangling references? It would seem that xvalues do not have their lifetime extended when assigned to a rvalue reference lvalue like in the question. However when I do this

#include <iostream>

using namespace std;

class Something {
public:
    Something() {
        cout << "Something()" << endl;
    }
    Something(const Something&) {
        cout << "Something(const Something&)" << endl;
    }
    Something(Something&&) {
        cout << "Something(Something&&)" << endl;
    }
    ~Something() {
        cout << "~Something()" << endl;
    }

    int a;
};

Something make_something() {
    return Something{};
}

int main() {
    auto&& something = make_something().a;

    return 0;
}

The lifetime of the object returned by a call to make_something is extended, even though make_something().a is an xvalue as per http://ift.tt/1qVqE9J (the third bullet in the xvalues explanation lists the member access I have above as an xvalue,)

a.m, the member of object expression, where a is an rvalue and m is a non-static data member of non-reference type;

If value categories do not determine when the lifetime of an rvalue will be extended then what does? I am having a hard time understanding when the lifetime of an rvalue is extended in C++

Aucun commentaire:

Enregistrer un commentaire