C++ const_cast неожиданный результат ⇐ C++
-
Anonymous
C++ const_cast неожиданный результат
Out of curiosity I executed that simple code:
#include int main() { const int cValue{32}; const int* pcValue = &cValue; int* pValue = const_cast(pcValue); *pValue = 16; assert(&cValue == pcValue); assert(&cValue == pValue); assert(*pcValue == 16); assert(*pValue == 16); assert(cValue == 16); // Ooops! cValue is 32. } I can see that pValue and pcValue both points on the same memory address as &cValue, but, interestingly, changing the value by that address doesn't affect cValue (at the same time Memory Viewer states that a corresponding memory block was modified). Just interesting how it works and is this a UB or not.
Источник: https://stackoverflow.com/questions/780 ... ng-outcome
Out of curiosity I executed that simple code:
#include int main() { const int cValue{32}; const int* pcValue = &cValue; int* pValue = const_cast(pcValue); *pValue = 16; assert(&cValue == pcValue); assert(&cValue == pValue); assert(*pcValue == 16); assert(*pValue == 16); assert(cValue == 16); // Ooops! cValue is 32. } I can see that pValue and pcValue both points on the same memory address as &cValue, but, interestingly, changing the value by that address doesn't affect cValue (at the same time Memory Viewer states that a corresponding memory block was modified). Just interesting how it works and is this a UB or not.
Источник: https://stackoverflow.com/questions/780 ... ng-outcome
Мобильная версия