I have a
class A
{
private:
static const int b = 10;
public:
static void testReadOnly(int _b)
{
const_cast<int &>(A::b) = _b;
}
};
and I want to test whether the member variable b
is initialized at compile time and therefore stored in the code-segment
(read-only).
To do so, I try to change the value of b
, which should produce some sort of runtime error (i.e. Segmentation fault, thrown by the MMU), if it actually is stored in the code-segment
.
I supposed that above code should build, but my compiler/linker tells me undefined reference to 'A::b'
Why?
Put a definition for the static member, outside of class declaration to solve linkage errors:
class A
{
static const int b = 10;
...
};
const int A::b;
~~~~~~~~~~~~~~~
In addition, any modification of a constant value (by weird castings) will invoke undefined behavior.
Undefined behavior is a unknown behavior, sometimes causes to crash the application, sometimes not.