Modifying mutable data via const references.
Hello,
Recently, in this newsgroup, I learned that if you bind an object to a
const reference, like this:
SomeObject a;
const SomeObject &ca = a;
And also like this:
void function (const SomeObject &ca);
SomeObject a;
function(a);
The compiler is completely free to create a copy of the object and
pass a reference to that copy instead, if it wants. I may be wrong
about this. However, if I'm not, does that mean that the following
code produces undefined results:
struct SomeObject {
mutable int n;
};
void elsewhere (void) {
SomeObject s;
const SomeObject &c = s;
c.n = 3; // <--- is it possible this doesn't change s.n?
}
void function (const SomeObject &s) {
s.n = 3; // <--- same deal here.
}
Will modifying mutable members of objects through const references not
necessarily modify that member in the object you assigned the
reference to (since the compiler may have created a copy, and you are
modifying the copy instead)?
What about something like this (same definition of SomeObject as
above) (in general, I know I am leaving a lot out of this snippet):
std::set<SomeObject>::const_iterator ci = SomeObjects.find(SomeKey);
(*ci).n = 3;
Is it possible that that code would not change the 'n' member of the
object in the set?
I also learned recently that the compiler is free to create a copy of
an object when casting away it's const, such as when using
const_cast<> or a C-style cast. Does that mean that the following is
undefined (a contrived example, I know):
struct SomeObject {
int n;
void SetNTo3 (void) { n = 3; }
};
void function (const SomeObject &c) {
(const_cast<SomeObject &>(c)).SetNTo3();
}
Is it possible that the const_cast will have caused a copy of 'c' to
be created, and so SetNTo3() applies to a different, temporary
instance?
Thanks,
Jason