首页 > 其他分享 >RAII

RAII

时间:2023-04-23 11:44:28浏览次数:55  
标签:resource RAII 资源 内存 memory Rust

(一)概念

RAII全称是Resource Acquisition Is Initialization,翻译过来是资源获取即初始化,RAII机制用于管理资源的申请和释放。对于资源,我们通常经历三个过程,申请,使用,释放,这里的资源不仅仅是内存,也可以是文件、socket、锁等等。

当一个对象创建的时候,自动调用构造函数,当对象超出作用域的时候会自动调用析构函数。

RAII的做法是使用一个对象,在其构造时获取对应的资源,在对象生命期内控制对资源的访问,使之始终保持有效,最后在对象析构的时候,释放构造时获取的资源。

如网络套接字、互斥锁、文件句柄和内存等等,它们属于系统资源。使用RAII对这些资源进行管理。智能指针(std::shared_ptr和std::unique_ptr)即RAII最具代表的实现,使用智能指针,可以实现自动的内存管理,再也不需要担心忘记delete造成的内存泄漏。

The Perils Of Ownership Based Resource Management (OBRM)

OBRM (AKA RAII: Resource Acquisition Is Initialization) is something you'll interact with a lot in Rust. Especially if you use the standard library.

Roughly speaking the pattern is as follows: to acquire a resource, you create an object that manages it. To release the resource, you simply destroy the object, and it cleans up the resource for you. The most common "resource" this pattern manages is simply memoryBoxRc, and basically everything in std::collections is a convenience to enable correctly managing memory. This is particularly important in Rust because we have no pervasive GC to rely on for memory management. Which is the point, really: Rust is about control. However we are not limited to just memory. Pretty much every other system resource like a thread, file, or socket is exposed through this kind of API.

(二)原理

1.栈

英文名称 stack, 在内存管理的语境下,指的是函数调用过程中产生的本地变量和调用数据的区域。 这个栈和数据结构里的栈高度相似,都满足后进先出(last-in-first-out 或 LIFO)。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

标签:resource,RAII,资源,内存,memory,Rust
From: https://www.cnblogs.com/imreW/p/17346060.html

相关文章

  • C++:实现RAII机制
    RAII,也称资源获取即初始化,要求资源的有效期与持有资源的对象的生命期严格绑定,不会出现内存泄漏等问题。我们尝试将指针封装到RAII类中,实现自动析构。#include<iostream>usingnamespacestd;template<typenameT>classRAII{public: RAII():data(nullptr){} explic......
  • C++| 1-RAII
     RAII,完整的英文是ResourceAcquisitionIsInitialization,是C++所特有的资源管理方式。RAII依托栈和析构函数,来对所有的资源——包括堆内存在内——进行管理。对......