Читаем Rust by Example полностью

==26873== total heap usage: 1,013 allocs, 1,013 frees, 8,696 bytes allocated

==26873==

==26873== All heap blocks were freed -- no leaks are possible

==26873==

==26873== For counts of detected and suppressed errors, rerun with: -v

==26873== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

No leaks here!

<p id="destructor"><strong><a l:href="#destructor">Destructor</a></strong></p>

The notion of a destructor in Rust is provided through the Drop trait. The destructor is called when the resource goes out of scope. This trait is not required to be implemented for every type, only implement it for your type if you require its own destructor logic.

Run the below example to see how the Drop trait works. When the variable in the main function goes out of scope the custom destructor will be invoked.

struct ToDrop;

impl Drop for ToDrop {

fn drop(&mut self) {

println!("ToDrop is being dropped");

}

}

fn main() {

let x = ToDrop;

println!("Made a ToDrop!");

}

הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

<p id="see_also_45"><strong><a l:href="#see_also_45">See also:</a></strong></p>

Box

<p id="ownership_and_moves"><strong><a l:href="#ownership_and_moves">Ownership and moves</a></strong></p>

Because variables are in charge of freeing their own resources, resources can only have one owner. This also prevents resources from being freed more than once. Note that not all variables own resources (e.g. references).

When doing assignments (let x = y) or passing function arguments by value (foo(x)), the ownership of the resources is transferred. In Rust-speak, this is known as a move.

After moving resources, the previous owner can no longer be used. This avoids creating dangling pointers.

// This function takes ownership of the heap allocated memory

fn destroy_box(c: Box) {

println!("Destroying a box that contains {}", c);

// `c` is destroyed and the memory freed

}

fn main() {

// _Stack_ allocated integer

let x = 5u32;

// *Copy* `x` into `y` - no resources are moved

let y = x;

// Both values can be independently used

println!("x is {}, and y is {}", x, y);

// `a` is a pointer to a _heap_ allocated integer

let a = Box::new(5i32);

println!("a contains: {}", a);

// *Move* `a` into `b`

let b = a;

// The pointer address of `a` is copied (not the data) into `b`.

// Both are now pointers to the same heap allocated data, but

// `b` now owns it.

// Error! `a` can no longer access the data, because it no longer owns the

// heap memory

//println!("a contains: {}", a);

// TODO ^ Try uncommenting this line

// This function takes ownership of the heap allocated memory from `b`

destroy_box(b);

// Since the heap memory has been freed at this point, this action would

Перейти на страницу:

Похожие книги

Компьютерные сети. 6-е изд.
Компьютерные сети. 6-е изд.

Перед вами шестое издание самой авторитетной книги по современным сетевым технологиям, написанное признанным экспертом Эндрю Таненбаумом в соавторстве со специалистом компании Google Дэвидом Уэзероллом и профессором Чикагского университета Ником Фимстером. Первая версия этого классического труда появилась на свет в далеком 1980 году, и с тех пор каждое издание книги неизменно становилось бестселлером. В книге последовательно изложены основные концепции, определяющие современное состояние компьютерных сетей и тенденции их развития. Авторы подробно объясняют устройство и принципы работы аппаратного и программного обеспечения, рассматривают все аспекты и уровни организации сетей — от физического до прикладного. Изложение теоретических принципов дополняется яркими, показательными примерами функционирования интернета и компьютерных сетей различного типа. Большое внимание уделяется сетевой безопасности. Шестое издание полностью переработано с учетом изменений, произошедших в сфере сетевых технологий за последние годы, и, в частности, освещает такие технологии, как DOCSIS, 4G и 5G, беспроводные сети стандарта 802.11ax, 100-гигабитные сети Ethernet, интернет вещей, современные транспортные протоколы CUBIC TCP, QUIC и BBR, программно-конфигурируемые сети и многое другое.

Дэвид Уэзеролл , Ник Фимстер , Эндрю Таненбаум

Учебные пособия, самоучители