3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C++で許されるけど、Rustで怒られること(参照)

Last updated at Posted at 2019-12-18

C++とRustを比較する

C++やってるけど、「Rustって安全だよ」って言われて興味を持った人向け。
用語はC++視点で。

ポインタが指している内容を変更する

C++

main.cpp
# include <iostream>

int main()
{
    int num = 123;
    int *num_p = &num;
    
    num = 234;
    
    std::cout << "num = " << num << std::endl;
    std::cout << "num_p = " << *num_p << std::endl;
}

Output

num = 234
num_p = 234

Rust

main.rs
fn main() {

    let mut num = 123; //mutって書かないと変更できないよ!
    let num_p = &num;
    
    num = 234;
    
    println!("num = {}", num);
    println!("num_p = {}", num_p);
    
}

error[E0506]: cannot assign to num because it is borrowed

 --> src/main.rs:6:5
  |
4 |     let num_p = &num;
  |                 ---- borrow of `num` occurs here
5 |     
6 |     num = 234;
  |     ^^^^^^^^^ assignment to borrowed `num` occurs here
...
9 |     println!("num_p = {}", num_p);
  |                            ----- borrow later used here

num_pポインタはnumを指しているから、numを書き換えてしまうと、num_pが意図したものでないかもしれない。

Rustに黙らせるコード(C++的にする)

unsafeです。C++erの理解のためです。
できるだけ使わないようにしましょう。

main.rs
fn main() {

    let mut num = 123;
    let num_p = &num as *const i32;
    
    num = 234;
    
    println!("num = {}", num);
    
    unsafe{
        println!("num_p = {:?}", *num_p);
    }
}

Rustに黙らせるコード(Cloneする)

main.rs
fn main() {

    let mut num = 123;
    let num_p = num.clone();
    
    num = 234;
    
    println!("num = {}", num);
    println!("num_p = {}", num_p);
    
}

もちろん別の値になる
Output

num = 234
num_p = 123

RustでもC++と似たような挙動にする

コンパイルは通るし、動く。使うところは考えましょう。

main.rs
use std::cell::Cell;

fn main() {

    let num = Cell::new(123);
    let num_p = &num;

    num.set(234);

    println!("num = {}", num.get());
    println!("num_p = {}", num_p.get());

}

Output

num = 234
num_p = 234
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?