Rvalue reference as an object field

#include <iostream>  
struct Bar
{
    int nb_;
    Bar(int nb) :nb_(nb){}
    ~Bar()
    {
        std::cout << "~Bar" << "\n";
    }
}; 

struct Foo
{    
    template<class T>
    Foo(T&& param) :bar_(std::move(param))
    {
        std::cout << "Foo" << "\n";
    } 
    ~Foo()
    {
        std::cout << "~Foo" << "\n";
    }

    Bar&& bar_;
};

int main()
{       
    { 
        Foo foo(Bar(1));
    }

    std::cin.ignore();
}

//Output:
Foo
~Bar 
~Foo

Is this program legal C ++? Can bar_ become a dangling link after completing the Foo constructor?

If this is not legal in terms of the C ++ standard, when is it useful to have an rvalue reference as a field?

+4
source share
2 answers

Will it bar_become a sagging link after completing the Foo constructor?

Not really. He becomes a dangling link at the point where the temporary creature is Bar(1)destroyed: at the end of the full expression Foo foo(Bar(1)).

It also shows an example of using rvalue link elements, for example forward_as_tuple:

struct woof
{
    using my_tuple = std::tuple<std::vector<int>, std::string>;
    my_tuple m;

    woof(my_tuple x) : m(std::move(x)) {}
};

std::vector<int> v{1,2,3,4,5};
woof w( forward_as_tuple(std::move(v), std::string{"hello world"}) );

forward_as_tuple rvalue (: tuple<vector<int>&&, string&&>), ctor woof v , std::string{"hello world"}.

+6

, bar_ .

, . , . , , - .

,

Bar b( 1 );
Foo foo(std::move(b));

foo b, . b . foo, , b .

+2

All Articles