4 ms·
That example doesn't mean references in C++ can be null any more than the following example means that Rust references can be null: fn function_with_refere
by kaashif 2y ago
That example doesn't mean references in C++ can be null any more than the following example means that Rust references can be null:
fn function_with_reference(reference: &i64) -> i64 {
reference.clone()
}
pub fn main() {
unsafe {
let x = 0 as *mut i64;
function_with_reference(&*x);
}
}
This also compiles, runs, and segfaults. And it doesn't mean that references in Rust can be null - they can't.
Your problem is with undefined behaviour or perhaps raw pointers, but not references. The reference itself isn't what's messing this up!
- kazinator 2y agoThe C++ code though, compiles, runs and doesn't segfault. That way of obtaining a null reference is actually quite portable. Where you going to run aground is when you have some null reference in some scope, and you have some code conditional on it being null. Yet the optimizing compiler assumes that since a reference is being checked for having a null address that comparison is always false.