why is the value being changed even in a const function?
#include<iostream>
using namespace std;
class temp
{
int value1;
public :
void fun() const
{
((temp*)this)->value1 = 10;
}
void print()
{
cout<<value1<<endl;
}
};
int main()
{
temp t;
t.fun();
开发者_开发百科 t.print();
}
Because you're casting away const
...
When you cast something, the responsibility is yours for making sure that it doesn't do something dumb.
Note that if temp t;
is changed to const temp t;
, you get undefined behavior, for modifying a const
value.
Coincidentally I literally just touched on this in my blog. (Almost the same function, too.)
$5.4/5 is about explicit type conversion
(which is what is being used here)
The conversions performed by
— a const_cast (5.2.11),
— a static_cast (5.2.9),
— a static_cast followed by a const_cast,
— a reinterpret_cast (5.2.10), or
— a reinterpret_cast followed by a const_cast,
can be performed using the cast notation of explicit type conversion. The same semantic restrictions and behaviors apply. If a conversion can be interpreted in more than one of the ways listed above, the interpretation that appears first in the list is used, even if a cast resulting from that interpretation is ill-formed. If a conversion can be interpreted in more than one way as a static_cast followed by a const_cast, the conversion is ill-formed.
In this case, ((temp*)this)
got treated as (const_cast<temp *>(this))
and was well-formed. This removed away the constness, thereby allowing to change the class member value.
C++ tries to prevent accidental errors, but it doesn't go out of its way to fight a programmer who's determined to have things their own way. If you use cast operators you're telling it "trust me, I know what's there", demanding it ignore it's own knowledge of the program. It's precisely because the C-style casting operator you've used is dangerous and can be easily misused that C++ introduces static_cast, const_cast and reinterpret_cast, which communicate the programmer's intent in such a way that the compiler can still say "hey, hold on there, that'd require more than just the type of leniency you're asking for". reinterpret_cast is the big daddy though... no arguing with that... just as brutal as the C-cast and rarely needed in a high-level application. Precisely because it's rarely needed, verbose and easily seen, it draws scrutiny. Code littered with C-style casts can easily hide bugs.
精彩评论