Recently I decided to dive into the C++ Standard and check whether certain code snippets are well defined and where to find those definitions in the standard. Since the standard is rather hard to get right (especially if you are not used to it) I wanted to verify if my assumption is right.
I came across the following example (which is obviously a bad idea). It compiles just fine (using g++ 8.2.1) but SEGFAULTs during execution:
#include <iostream>
static const int staticInt = 23;
int main () {
int &localInt = const_cast<int &>(staticInt);
localInt = 11;
std::cout << staticInt << std::endl;
return 0;
}
So, I searched through the standard (I use the working draft on open-std btw) and found paragraph 6.8.10:
Creating a new object within the storage that a const complete object with static, thread, or automatic storage duration occupies, or within the storage that such a const object used to occupy before its lifetime ended, results in undefined behavior.
Am I right, that this paragraph is applicable for the given example? If I am not, where else should I look at?
staticInt
, so it can't possibly apply. – Marylnmarylouconst
variables. You attempt to modify aconst
variable, which leads to UB. End of story. That it isstatic
or in the global scope or that you use a reference to the variable or that the reference is in a different scope is irrelevant. – Magnesia