Re: GotW #88: Is it safe to const_cast a reference to a temporary?
* Alf P. Steinbach:
* Niels Dekker - no return address:
Herb Sutter wrote a new Guru-of-the-Week column last month, GotW #88,
about binding a temporary object to a reference-to-const. Now if this
temporary isn't const, is it safe to const_cast the reference?
#include <string>
#include <cassert>
using std::string;
string f() { return "abc"; }
void h() {
const string& s1 = f();
const string& s2 = s1;
const_cast<string&>(s1) = "new value!"; // Safe?
Not in standard C++, although it might be safe with a particular compiler.
The short of it is that you're misinforming the compiler, and the almost
as short of it is that the compiler is free to optimize away the call to
f and e.g. substitute the value string("abc") wherever s1 and s2 are used.
Except for taking address, which includes passing by reference, which
applies to just about anything it could be used for.
I didn't think of that.
And I'm not sure there is any qualification of "used" that would make
the last statement above true.
Sorry about hasty trigger finger -- correcting this before Someone
Else does.
However, rest applies:
The bit-longer of it is that the temporary was const to begin with (the
temporary bound to the reference, not the temporary returned by the
function, although they might end up being the same), and you can't cast
away /original/ const'ness with portable well-defined result.
assert(s1 == "new value!"); // Okay?
assert(s2 == "new value!"); // Okay?
}
See also:
GotW #88 - A Candidate For the "Most Important const."
http://herbsutter.spaces.live.com/blog/cns!2D4327CC297151BB!378.entry
Would IMHO be better if Herb posted his GotW questions here, as he did
for the first few, and summarized the responses + his extra insights
(AFAIK the PIMPL idiom GOTW with erronous auto_ptr still not corrected).
Cheers, & hth.,
- Alf (wondering why the Send button doesn't say "Do you Really want to
Send?")
--
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?