RAII -- Resource Acquisition Is Initialization

本文介绍了资源获取即初始化(RAII)设计模式,这是一种在C++等面向对象编程语言中常用的资源管理技术。通过在对象的构造函数中获取资源并在析构函数中释放资源,可以确保即使在发生错误的情况下也能正确地释放资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 RAII,资源获取即初始化。

这个东西本不是什么高深的东西,日常写代码时也经常用到,其实就是将资源与对象的生命周期绑定,具体的做法就是在构造函数中初始话资源,在析构函数中释放资源,这样使用这个对象的时候甚至无需手动对其进行任何内存操作,从而保证内存不会泄露。

wiki的一段:

Resource Acquisition Is Initialization, often referred to by the acronym RAII (or, erroneously, RIIA), is a popular design pattern in several object oriented programming languages like C++D and Ada. The technique was invented by Bjarne Stroustrup,[1] to deal with resource deallocation in C++. In this language, the only code that can be guaranteed to be executed after an exception is thrown are the destructors of objects residing on the stack. Resources therefore need to be tied to the lifespan of suitable objects. They are acquired during initialization, when there is no chance of them being used before they are available, and released with the destruction of the same objects, which is guaranteed to take place even in case of errors.

RAII is vital in writing exception-safe C++ code: to release resources before permitting exceptions to propagate (in order to avoid resource leaks) one can write appropriate destructors once rather than dispersing and duplicating cleanup logic between exception handling blocks that may or may not be executed.

http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值