5 ms·
Analogous example in C++11, using unique_ptr (which Rust's owned pointer models): #include <stdio.h> #include <memory> void destroyer(std::unique_
by pbsd 13y ago
Analogous example in C++11, using unique_ptr (which Rust's owned pointer models):
#include <stdio.h>
#include <memory>
void destroyer(std::unique_ptr<int> x)
{
printf("%d\n", *x);
// x is deallocated here
}
int main()
{
auto x = std::make_unique<int>(3);
// destroyer(x); ERROR: ownership must be transferred explicitly
destroyer(move(x)); // Override with an explicit move
printf("%d\n", *x); // Guaranteed to segfault
return 0;
}
This is somewhat more helpful, but sadly the compiler cannot monitor the state of x at compile time, like Rust. The upside is that this bug is easy to catch since the invalid access is guaranteed to try to access a null pointer, and will crash instead of giving garbled results.
- pcwalton 13y ago> The upside is that this bug is easy to catch since the invalid access is guaranteed to try to access a null pointer, and will crash instead of giving garbled results. GCC and LLVM optimize based on the assumption that null pointers are never dereferenced, so this is actually undefined behavior, no? Anything can happen.
- pbsd 13y agoYou're right that it's UB, good point. It's hard to think what a sane compiler would do in this case besides going through with the dereference, though.
- dbaupp 13y agoA pointer dereference allows the compiler to assume that a pointer is non-NULL, so it can then perform "invalid" optimisations (like dead-code removal), this post contains an very small example: http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html http://blog.llvm.org/2011/05/what-every-c-programmer-should-...
- bjz_ 13y agoDoes `unique_ptr` incur a run-time peanalty for those checks?
- pbsd 13y agoFor all intents and purposes no. unique_ptr is nothing more than a pointer container that disables copying but allows moving. Therefore only one unique_ptr should be owning a pointer at any given time (unless, like everything in C++, you go around it).