by lifthrasiir · 12y ago · 0 comments
I may be wrong, but my understanding is that Rust's constants are actually constant, and proved as such by the compiler, which is a major difference over C++.
#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.Yes and that's a huge trap, which is why I'm so annoyed that D has copied 'const' from C++ instead of renaming it to 'view' or 'read'..