Re:Rust for C++ programmers – part 4: unique pointers
by nly on Tuesday April 29, 2014 @10:19AM
(#7667111)
This is because delete is an operator that can be overridden, and whether it has been overridden isn't known until link time.
void operator delete(void*) { }
int main()
{
int on_stack;
int& ref = on_stack;
int* ptr = &ref;
delete ptr;
return 0;
}
and now it's safe :P... and yes, never freeing any memory is arguably a perfectly valid memory management strategy. Ok, this example is nuts... but it's a feature of C++, in the C tradition, that it lets you do crazy things. Can I plug custom per-type memory allocators in to Rust?
But all of that are patterns of use, enforced mostly by convention. In Rust, that's enforced by the language itself, and violating it will be a compiler error. The following kind of shenanigans won't be allowed outside of unsafe regions:
Yes, it's obviously bad code, but C++ happily let me write it, and it compiled with no warnings under -Wall -Wpedantic.