gopal wrote:
Hi, i am now reading thru the thinking in C++ and i have some doubts
"Doubts"? About what?
at section CONST REFERENCES as
The use of const references in function arguments is especially
important because your function may receive a temporary object.
A non-const reference cannot be bound to a temporary. That's a C++
language requirement.
This might have been created as a return value of another function
or explicitly by the user of your function. Temporary objects are
always const,
That is simply not true. Disallowing of binding non-const references
to temporaries has *nothing* to do with possible constness of the
temporary object. Besides, in most cases temporaries are *not* at all
constant.
so if you don't use a const reference, that argument
won't be accepted by the compiler. As a very simple example,
page - 498 , chapter 11, Ref & Copy ctor,
can any pls make me understand this. I tried reading thru again &
again, but i am not able to understand. This was foll by example which
i could not understand
What exactly *could not* you understand?
//: C11:ConstReferenceArguments.cpp
// Passing references as const
478 Thinking in C++ www.BruceEckel.com
void f(int&) {}
void g(const int&) {}
int main() {
//! f(1); // Error
g(1);
} ///:~
Pls clarify
In 'f(1)' expression the temporary behind the numeric literal 1, which
is created at some point before calling the function and is destroyed
right after full expression evaluation, cannot be bound to a reference
to non-const 'int' as calling 'f' would require. That's why the compiler
reports an error here.
The explanation is a bit more convoluted than that temporaries are const.
They are not. The reason is that during binding a temporary to a reference
another temporary can be created if needed for proper type matching. For
example:
void f(double& d);
foid g(double const& d);
f(1); // '1' is integer
g(1); // '1' is integer
Now, if 'f' wanted to try to change its argument, and a temporary of type
'double' were created, then the change would never be propagated to the
temporary associated with it, since there would be another, intervening,
temporary. That's why it was decided to only allow references to const
to bind to a temporary.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask