JensB
JensB

Reputation: 939

Why is it possible to use rvalue references as members without lifetime problems?

Sometimes I see people using rvalue references as members and I always wonder how this is possible and how it doesn't lead to lifetime problems. Take this as an example:

class Foo
{
public:
    Foo(int&& i)
      : i_(std::move(i))
    {
    }
    void printNum()
    {
        std::cout << i_ << std::endl;
    }
private:
    int&& i_;
};


int main()
{
    Foo f{5};
    f.printNum(); // Outputs 5 every time
}

In what scope does the integer 5 exist in this example? The rvalue passed to the Foo-constructor has surely been destructed when the next line is called, so why doesn't the call to printNum warrant undefined behavior? Are we not trying to access memory that's no longer in use?

Upvotes: 2

Views: 63

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

The int is destroyed at the end of the expression Foo f{5}; so the program has undefined behavior.

Upvotes: 4

Related Questions