【Rust】ヒープ領域

ヒープ領域とは、プログラム実行時に動的にメモリを割り当てるための領域
ヒープ領域は関数が終わっても存在することができ、所有者が居なくなった時点で解放される

1
2
3
4
5
6
7
8
9
struct Point {
    x: i32,
    y: i32,
}
 
fn main(){
    let p: Box<Point> = Box::new(Point {x:100, y:200});
    println!("{} {}", p.x, p.y);
}

new演算子、std::vectorはヒープ領域を使用している。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <limits>
#include <exception>
 
int main()
{
    std::cout << std::hex << std::numeric_limits<uintptr_t>::max() << std::end;
 
    try {
        char* temp= new char[std::numeric_limits<uintptr_t>::max()];
        std::cout << temp << "\n";
    }
    catch(std::bad_alloc& e){
        std::cout << e.what() << "\n";
    }
 
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <limits>
#include <exception>
 
int main()
{
    int* array = new int[5];
 
    for(int i = 0; i < 5; ++i){
        array[i] = i*i;
    }
 
    delete[] array;
    array = nullptr;
    return 0;
}

いまいちboxの使い所と書き方がわかりませんな…