Re: non-const refs to const objects
marco.guazzone@gmail.com wrote:
On Apr 30, 4:13 am, gnepp...@web.de wrote:
Hi all,
as I've come to learn it, casting away constness from objects that are
actually const results in Undefined Behaviour.
The safe way of modifying data members from within const member
functions is declaring the data member "mutable".
So what about the following code which uses neither suspicious-looking
"const_casts" nor "mutable", and still modifies a const object. Is it
UB? I'm confused...
struct Bar
{
Bar()
{
mutable_this = this;
}
void modify() const
{
mutable_this->value=42;
}
Bar* mutable_this;
int value;
};
const Bar bar;
int main()
{
bar.modify();
}
This is OK for two reasons:
* in a "const" method the "this" get to a "const Bar*" to the class
while "mutable_this" remains a "Bar*"
But the point is that on exit from the ctor *mutable_this has undefined
behaviour because it points to a const Bar. At the time the definition
is executed the code is valid but on exit from the ctor it ceases to be.
* the change to "mutable_this->value" is legal since in the const
method what you were not allowed to change was the pointer not the
pointed value.
Valid in the sense that the error is not diagnosable but because the
programmer has lied to the compiler (tricking it into providing a plain
pointer to a const object) the code has undefined behaviour.
So, this is OK:
void modify() const
{
mutable_this->value=42;
}
while this NOT:
void modify() const
{
mutable_this=new Bar();
}
Cheers,
True, but so what?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]