top | item 10291359

(no title)

keyneus | 10 years ago

C++14:

  auto p = std::make_unique<int>(5);
  auto q = std::move(p);
  std::cout << *p << std::endl;
Segfault using the “safe” C++ features. I'm a fan of modern C++, but it's not safe (in a Rust sense) even if you stick to C++11/C++14 features.

discuss

order

steveklabnik|10 years ago

For comparison, the same thing in Rust:

  fn main() {
      let p = Box::new(5);
      let q = p;
      println!("{}", p);
  }

gives, upon compiling:

    error: use of moved value: `p` [E0382]
    println!("{}", p);
                   ^
    note: in this expansion of format_args!
    note: in this expansion of print! (defined in <std macros>)
    note: in this expansion of println! (defined in <std macros>)
    help: run `rustc --explain E0382` to see a detailed explanation
    note: `p` moved here because it has type `Box<i32>`, which is moved
    by default
    let q = p;
        ^
    help: if you would like to borrow the value instead, use a `ref`
    binding as shown:
    let ref q = p;
    error: aborting due to previous error
Running `rustc --explain E0382` or going to https://doc.rust-lang.org/nightly/error-index.html#E0382 gives you an extended error message as well.