Hacker News new | ask | show | jobs
by steveklabnik 3718 days ago
uniqe_ptr does not "track lifetimes".

For example, this Rust program:

  fn main() {
       let r: &i32;

      {
          let b = Box::new(i32);
          r = &*b;
      }

      // r is dangling here, this would be bad:
      println!("{}", r);
  }
Is caught at compile time. Rust keeps track of the lifetime of both b and r, and knows that r will be dangling.

The C++ version:

  #include<iostream>
  #include<memory>

  using namespace std:

  int main() {
      int *r;

      {
          uniq_ptr<int> b(new int(5));
 
          r = &*b;
      }

      // r is dangling here
      cout << r << endl
  }
This compiles with no warnings under -Wall -Wextra with no warnings, and happily does whatever you ask with r, even though it's dangling.

Yes, this specific example is a bit contrived, but such is the way of examples. My point is just that C++'s smart pointers are a great thing, but that doesn't mean they do everything that Rust's do.