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?