Re: GotW #88: Is it safe to const_cast a reference to a temporary?
* steady.li@gmail.com:
by the way , I tested what you are dicussing using VC2005 but find
another problem that confused me. who can help me understand it?
int a = 1;
const int& b= 1; // legal //using the mechanism is using const
reference to temporary.
//int& c = 1; //illegal // why? but according to what you talked ,
it is not the rule though, it can
be supported by VS2005, just like
I think you mean, why is it disallowed by the standard, when there
exists at least one compiler that does support it (for class type
objects) as a language extension, showing by example that it could in
principle be allowed.
One example is
void foo( int& x ) { x = 666; }
int main()
{
foo( 42 );
}
One would want this to not compile.
Another example involves implicit type conversion, where the object
modified is not the actual argument but a temporary created from the
actual argument. One would want that also to not compile, instead of
silently doing nothing. However, the problem could be avoided by
disallowing automatic creation of a temporary for such arguments.
The short summary is that disallowing that binding is practically
useful, whereas allowing it (as it was originally) turned out to create
a host of problems.
The Annotated Reference Manual (a.k.a. the "ARM") says of the earlier
more permissive rule that it was "a major source of errors and surprises".
string& s1 = f();
This is invalid unless f() returns a reference or an object convertible
to reference.
int& d= a; //legeal
const int& e = a; //legal // why it is legal? const reference also
can point to non-const content memory?
Yes. It doesn't make that object const in itself. It just restricts
what you can do with the object via the reference.
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?