"Alex Vinokur" <al****@big-foot.com> wrote in message
news:36*************@individual.net...
"Ivan Vecerina" <IN*************************@vecerina.com> wrote in
message news:ct**********@news.hispeed.ch... > Foo(300) = Foo(500); // Foo(300) is const. Why does a compiler
> compile
> that?
Foo(300) is not const - it is a temporary.
---------------------------------------- It is true that temporaries can be bound to a const reference only
(not to a non-const ref).
If 'Foo(300) = Foo(500);' is legal, why can temporaries be bound
to a const reference only (not to a non-const ref)?
Probably to avoid programming errors such as:
copySomeMembers( myTargetVariable, getSomeTemporary() );
//woops: actually, the functions takes 1st source, 2nd destination:
// copySomeMembers( Foo const& src, Foo& dst );
Because temps can only be bound to a const reference, you cannot
accidentally pass a temporary for the output of a function.
I find this is a good thing, but some disagree.
However, it is legal to call any member function on a temporary.
And the line above is equivalent to:
Foo(300).operator=( Foo(500) );
On the other hand, it is sometimes convenient (and somewhat less
error prone) to write something like:
getSomeTermporaryHandle().doSomething();
And there is no special treatment for assignment operators,
which is just another member function.
I think a balance had to be chosen between convenence
and safety.
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form