简体   繁体   中英

Change value of static const int in c++

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;
};

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM