1

I need to change a value of a static const int member. I know it’s a bit stranger thing but I need it to overcome a limitation given by framework I’m using!

I’ve already try, but it doesn’t work, it rises an error saying “undefined reference to MyClass::staticConstMember”:

class MyClass
{
static const int staticConstMember = 10;
};
int main()
{
int* toChageValue = const_cast<int*>(&MyClass::staticConstMember);
 toChangeValue = 5;
std::cout<<MyClass::staticConstMember<<std::endl; // here I need to print 5
Return 0;
};
  • 7
    You're not allowed to change the value of a const object, and attempting to do it has undefined behaviour. You must solve your actual problem, whatever it is, in a different way. – molbdnilo Oct 07 '19 at 08:31
  • 1
    https://stackoverflow.com/questions/9110487/undefined-reference-to-a-static-member for the linker error, but as others have said, don't do it. – Mat Oct 07 '19 at 08:33
  • 1
    Why declaring as `const` a variable which is supposed to be modified ? It seems you have a design issue. Moreover I have the feeling that it's a [XY problem](https://en.wikipedia.org/wiki/XY_problem). What are you trying to achieve initially ? – Fareanor Oct 07 '19 at 08:39
  • "I need to change a value of a static const int member." Remove `const`, and then you will be able to change its value. – Eljay Oct 07 '19 at 12:04

1 Answers1

6

You can't. Period. An object which is actually defined with a const data type is immutable in C++ and compilers know this and utilise this knowledge.

You cannot hope to do that reliably. Even if you somehow manage to convince the bits in memory to actually change (using UB such as the cast you're trying), you can never be sure the compiler will issue load instructions from that memory instead of caching the load result or even hardcoding the value which the const object had at compile time.

Not to mention the fact that such an object (the static const int) can reside in a portion of memory for which your program does not have write access. Performing such an unsafe cast as you're trying would then crash your program with an access violation.

You will have to find a different way of achieving your actual goal.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455