add ownersystem examples

main
3029257 2026-10-12 11:10:40 +00:00
parent 9a5cd58b8c
commit bfc4055bde
5 changed files with 149 additions and 0 deletions

View File

@ -0,0 +1,26 @@
// $ rustc ownersystem_1.rs
// $ ./ownersystem_1
struct Bob {
n: Vec<i32>
}
impl Bob {
fn new() -> Bob {
Bob { n: Vec::new() }
}
}
fn func_1() {
let n = Bob::new();
func_2(n);
//is now out of scope as func_2 owns n now.
//println!("{}", bob.n[0]);
}
fn func_2(b: Bob) {
println!("{}", b.n[0]);
}
fn main() {
func_1();
}

View File

@ -0,0 +1,26 @@
// $ rustc ownersystem_2_borrowing.rs
// $ ./ownersystem_2_borrowing
struct Bob {
n: Vec<i32>
}
impl Bob {
fn new() -> Bob {
Bob { n: Vec::new() }
}
}
fn func_1() {
let n = Bob::new();
func_2(&n);
//is now in scope as func_2 just got a read only reference.
println!("{}", n.n[0]);
}
fn func_2(b: &Bob) {
println!("{}", b.n[0]);
}
fn main() {
func_1();
}

View File

@ -0,0 +1,33 @@
// $ rustc ownersystem_3_borrowing.rs
// $ ./ownersystem_3_borrowing
struct Bob {
n: Vec<i32>
}
impl Bob {
fn new() -> Bob {
Bob { n: Vec::new() }
}
}
fn func_1() {
let n = Bob::new();
let n1 = &n;
let n2 = &n;
func_2(n1);
func_3(n2);
//works because both func_2 and func_3 only got read only references
println!("{}", n.n[0]);
}
fn func_2(b: &Bob) {
println!("{}", b.n[0]);
}
fn func_3(b: &Bob) {
println!("{}", b.n[0]);
}
fn main() {
func_1();
}

View File

@ -0,0 +1,34 @@
// $ rustc ownersystem_4_mutable.rs
// $ ./ownersystem_4_mutable
struct Bob {
n: Vec<i32>
}
impl Bob {
fn new() -> Bob {
Bob { n: Vec::new() }
}
}
fn func_1() {
let mut n = Bob::new();
let n1 = &mut n;
// doesn't work because there is already a mutable borrowing
//let n2 = &n;
func_2(n1);
//func_3(n2);
//works because both func_2 and func_3 only got read only references
println!("{}", n.n[0]);
}
fn func_2(b: &mut Bob) {
println!("{}", b.n[0]);
}
fn func_3(b: &Bob) {
println!("{}", b.n[0]);
}
fn main() {
func_1();
}

View File

@ -0,0 +1,30 @@
// $ g++ -o raii raii.cpp
// https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization
#include <cstdio>
class MyClass {
int *n;
public:
MyClass(int x)
{
this->n = new int[x];
printf("constructor\n");
}
~MyClass()
{
delete this->n;
printf("deconstructor\n");
}
int* get_n()
{
return this->n;
}
};
int main()
{
MyClass *b = new MyClass(5);
int *xs = b->get_n();
printf("%d\n", xs[0]);
delete b;
printf("%d\n", xs[0]);
}