I understand that having a const
method in C++ means that an object is read-only through that method, but that it may still change otherwise.
However, this code apparently changes an object through a const
reference (i.e. through a const
method).
Is this code legal in C++?
If so: Is it breaking the const
-ness of the type system? Why/why not?
If not: Why not?
Note 1: I have edited the example a bit, so answers might be referring to older examples.
Edit 2: Apparently you don't even need C++11, so I removed that dependency.
#include <iostream>
using namespace std;
struct DoBadThings { int *p; void oops() const { ++*p; } };
struct BreakConst
{
int n;
DoBadThings bad;
BreakConst() { n = 0; bad.p = &n; }
void oops() const { bad.oops(); } // can't change itself... or can it?
};
int main()
{
const BreakConst bc;
cout << bc.n << endl; // 0
bc.oops(); // O:)
cout << bc.n << endl; // 1
return 0;
}
Update:
I have migrated the lambda to the constructor's initialization list, since doing so allows me to subsequently say const BreakConst bc;
, which -- because bc
itself is now const (instead of merely the pointer) -- would seem to imply (by Stroustrup) that modifying bc
in any way after construction should result in undefined behavior, even though the constructor and the caller would have no way of knowing this without seeing each others' definitions.
void (void)
is a deprecated construct sincevoid ()
has done the same thing since C++98 and C99. – PoikilothermicO:)
smiley has a double meaning as a happy angel and a shocked horrified face, depending on which direction you read it from. – Khartoum