2 ms·
Not only is it "read only," it's not even necessarily read only: #include <iostream> void f(const int* var) { *var = 42; } int main() { i
by scott_s 13y ago
Not only is it "read only," it's not even necessarily read only:
#include <iostream>
void f(const int* var)
{
*var = 42;
}
int main()
{
int* ptr = new int(78);
f(ptr);
std::cout << *ptr << std::endl;
return 0;
}
Compiling produces:
[scott_s@local Code] g++ const.cpp
const.cpp: In function ‘void f(const int*)’:
const.cpp:5: error: assignment of read-only location
But if we make it:
#include <iostream>
void f(const int* var)
{
int* sneaky = const_cast<int*>(var);
*sneaky = 42;
}
int main()
{
int* ptr = new int(78);
f(ptr);
std::cout << *ptr << std::endl;
return 0;
}
We get:
[scott_s@local Code] g++ const.cpp
[scott_s@local Code] ./a.out
42
C++ gives us escape hatches all over the place. I think that the modern approach of compartmentalizing all escape hatches into explicitly regions of "unsafe" code, and providing no escape hatches outside of such regions, is much better.
- deleted 13y ago[deleted]