Re: temporary object and const reference
Am 15.11.2012 06:12, schrieb zade:
codes like below:
struct Foo {};
void func(Foo&){
}
void test(){
func(Foo() = Foo()); // compile ok
func(Foo()); // compile error
}
Foo() generate a temporary object, which is a const reference object in c++. so why func(Foo() = Foo()) compile ok but func(Foo()) compile error.
A temporary object is not a "const reference object". What does that
even mean, "const reference object"? A reference is not an object and an
object is not a reference. Also, there is no "const" involved in Foo().
An expression has a type and a value category. The expression
Foo()
is of type Foo and is an "rvalue". As such you may not bind it to a
non-const lvalue reference. But you can work your way around that in
different ways:
struct Foo {
Foo& lvalue() {return *this;}
};
void sink(Foo&);
int main() {
sink(Foo().lvalue());
}
So, it is not specific to the assignment operator. If you're not
disabling this explicitly, non-static functions can be invoked on
temporaries. This means, at some point the adress of the temporary
object will be "bound" to a this pointer.
C++11 offers a way to turn this off:
struct Foo {
Foo& lvalue() & {return *this;}
// ^
// This is a ref qualifier
};
This makes the member function only applicable on non-const lvalue
objects. (Note: I said "non-const lvalue object" because I don't know
any better how to describe it. Of course, the lvalueness is not a
property of the object but a property of the expression that refers to
that object)
Cheers!
SG