question on r value reference

Hi,
Could someone explain?

For the following statement, why void foo(X const &) can be called on both r and l value, but void foo(X&) cannot. I faintly remember it is about reference binding on temporary, but not clear on the concept now.

Thanks


"
If you implement
void foo(X&);
but not
void foo(X&&);
then of course the behavior is unchanged: foo can be called on l-values, but not on r-values.

If you implement

void foo(X const &);

but not

void foo(X&&);

then again, the behavior is unchanged: foo can be called on l-values and r-values, but it is not possible to make it distinguish between l-values and r-values.
"
For example, suppose X is int and you define void foo(int &). Now suppose it's possible to bind int & to an rvalue. What should happen if you call foo(0)?
that will be a compiling error for temp variable. So what magic does void foo(int const &) do? Keep the lifetime of the temp through the lifetime of the function?
Well, yes, of course. It can be trivially shown that temporaries passed as function parameters live until their callee ends. There's nothing magic about that.
1
2
3
4
5
6
7
8
9
10
struct A{
    A(){ std::cout << "A::A()\n"; }
    ~A(){ std::cout << "A::~A()\n"; }
};

void foo(const A &a){
    std::cout << "foo()\n";
}

foo(A());
thanks
Topic archived. No new replies allowed.