#RAII

GripNewsGripNews
2025-11-12

🌘 C++ RAII 與錯誤處理的兩難:從 Bjarne 的範例談起
➤ 探索 C++ RAII 與錯誤處理的精妙平衡
marler8997.github.io/blog/bjar
本文深入探討 C++ 中資源獲取即初始化(RAII)與例外處理機制在實際應用中的潛在問題,特別是當操作可能失敗時。作者以 Bjarne Stroustrup 展示的 C++ 檔案開啟範例為引,說明 RAII 雖能確保資源釋放,但在處理檔案開啟失敗等常規錯誤時,若依賴例外處理,可能導致訊息不準確、例外捕獲不完全,以及資源獲取在第二次初始化(RAISI)的複雜性。文章對比了 C 語言以返回值處理錯誤的直觀性,並提出瞭解決 C++ RAII 相關錯誤處理問題的兩種方法:一是在建構子外進行可能失敗的操作,二是採用類似 `std::error_code` 的「側通道」機制,以期在保留 RAII 優勢的同時,提升錯誤處理的清晰度和可靠性。
+ 這篇文章讓我對 C++ 的例外處理有了更深的認識,尤其是在檔案操作
++

Christian Tietzectietze
2025-09-03

Inside of an actor, we can't assume `deinit` is isolated. If anything, we ought to assume the opposite.

Since there's no easy way to express "release all owned resources", the actual change I'm being nudged towards is: express ONLY resource ownership with a new type. There, you can use deinit.

This is from C++, but in Swift.

2025-04-21

[Перевод] Линус Торвальдс: Критика C++ — Комплексный анализ

Линус Торвальдс, создатель (и великодушный диктатор) Linux, всегда с особой критикой относился к C++, объясняя почему он отвергает его в разработке ядра Linux. Но он не просто резко высказывается против использования C++, а приводит ряд аргументов, которые мы с вами сегодня и рассмотрим.

habr.com/ru/companies/otus/art

#c++ #linux #Линус_Торвальдс #ядро_Linux #исключения_в_c++ #RAII #управление_памятью #ооп #абстракции_в_программировании

2025-04-15

RAII 2.0: RAII как архитектурный инструмент в C++

Идиома RAII — давно зарекомендовал себя как удобный способ автоматического управления ресурсами в C++. Обычно мы применяем его для управления памятью, файловыми дескрипторами или мьютексами. Однако что, если расширить понятие RAII до управления не только физическими ресурсами, но и логическими контрактами и состояниями системы? В этой статье я хочу поговорить о том, как RAII можно использовать для контроля жизненного цикла асинхронных операций, транзакций или подписок, гарантируя их корректное завершение или откат до прежнего состояния.

habr.com/ru/articles/901092/

#С++ #RAII #Жизненный_цикл #Подписки #Транзакции #Безопасность_кода #управление_ресурсами #паттерны #Логический_контракт

रञ्जित (Ranjit Mathew)rmathew
2024-12-08

The guys wade into the in the kernel brouhaha:

“RAII And The Rust/Linux Drama”, Loris Cro (kristoff.it/blog/raii-rust-lin).

On HN: news.ycombinator.com/item?id=4

On Lobsters (where Asahi Lina responds): lobste.rs/s/hxerht/raii_rust_l

Orhun Parmaksız 👾orhun@fosstodon.org
2024-11-06

Man, I wish Rust had the 'defer' keyword 😞
Wait...

🦀 **scopeguard**: A Rust library for a convenient RAII scope guard.

🌀 Has a defer! macro.

🔥 Runs a closure on scope exit, even if a panic occurs.

⭐ GitHub: github.com/bluss/scopeguard

#rustlang #library #defer #scope #raii #guard #programming #pattern #opensource

2024-06-18

C++OnSea 2024 SESSION ANNOUNCEMENT: The Surprising Power of Small Wrapper Classes by Jørgen Fogh

cpponsea.uk/2024/sessions/the-

Register now at cpponsea.uk/tickets/

#wrappers #softwaredesign #RAII #cpp #cplusplus

2024-05-17

C++OnSea 2024 SESSION ANNOUNCEMENT: The Surprising Power of Small Wrapper Classes by Jørgen Fogh

cpponsea.uk/2024/sessions/the-

Register now at cpponsea.uk/tickets/

#wrappers #softwaredesign #RAII #cpp #cplusplus

2024-04-17

Having worked a few weeks now with #C #code that uses __attribute__ (cleanup) , I am disappointed to say that it's an insignificant improvement.

Why?

Because you need to remember to annotate every variable, and sometimes cleanup is not what you want, leading to double-free.
At least the freeing is declared next to the variable, so that's nice.

But this still sucks compared to #RAII imposed on the type, where you don't need to remember.

#programming #coding #memory #safety

Audun Hallandaudunhalland@mas.to
2024-04-17

Resource acquisition is initialization.

Her blir det liv.

#raii #raii

CppConCppCon
2024-02-13

We have released a new CppCon 2023 Video!

Coroutine Patterns: Problems and Solutions Using Coroutines in a Modern Codebase – Francesco Zoffoli
youtu.be/Iqrd9vsLrak

2024-02-06

Blogged: Use Scope Guards to Prevent Resource Leaks

Modern #C++ has many neat #RAII-based solutions for managing resources. However, every now and then one needs to manually make sure that some code is run when a resource is not needed anymore. One great solution to this problem is a #ScopeGuard. I've surprisingly rarely seen them used in practice!

lukas-barth.net/blog/scope-gua

#cpp #cplusplus

(Note: Replies to this post will be visible as comments on the blog.)

2023-11-09

@jaredwhite Yeah I am wondering if it would make more sense to have a separate community protocol for initialization.

I'm very strongly of the opinion that you should never be able to get a reference to an uninitialized object (I think this is sometimes called #RAII?) Unfortunately that ship sailed for web components a long time ago. Constructors are worthless in this context too (and terrible per blog.dwac.dev/posts/ctor/). So maybe a protocol around initialization would help, whether that is or isn't `defer-hydration`.

Felix Palmen 📯zirias@techhub.social
2023-08-09

@jhx You asked for it, so I'll answer it:

Imho, C++ design is broken from the very beginning. It wanted to provide #OOP language constructs, still maintaining full #C compatibility (which already failed many years ago, cause the languages took different roads).

It combines #exceptions (IMHO generally a bad idea) with explicit resource management (an *awful* idea, forcing you to use #RAII which will in turn mandate creation of purely "technical" classes, just to manage resources).

It wanted #generics, but that's impossible without breaking C compatibility, so it came up with #templates, actually a #preprocessor on steroids.

Overloading also doesn't fit into the simple C library ABI (where #linker symbols are named just like the function), so it came up with "name mangling" ... which is especially horrific because it is *not* standardized.

Ah well, I could go on 😂

The 1414° Code Forge 🌍1414codeforge@mastodon.gamedev.place
2023-07-15

As much as we love #C, we've always felt the lack of a convenient #RAII feature in the language. Yet, many compilers allow to implement such feature with relatively little effort.

So, @micia thought to share such implementation, and our point of view on the subject, in a article.

We’ll be glad to hear your feedback and suggestions before we publish it on our website.

#CProgramming #Programming #software

codeberg.org/1414codeforge/art

1414 Code Forge 🇮🇹1414codeforge@mastodon.uno
2023-07-15

Il #C ci piace, ma sentiamo spesso la mancanza di un meccanismo di #RAII nel linguaggio. Per fortuna, molti compilatori consentono di implementarne uno con relativamente poco sforzo.

Perciò il buon @micia ha pensato di buttare giù un articolo per mostrare come farlo e spiegare il nostro punto di vista.

Qualcuno abbastanza volenteroso da condividere commenti e dirci se abbiamo sbagliato nulla, prima di pubblicarlo sul nostro sito?

#CProgramming #Programming

codeberg.org/1414codeforge/art

heise online (inoffiziell)heiseonline@squeet.me
2020-07-12
Heyerdahl war sicher, dass die Menschen schon im Altertum die Meere überqueren konnten. Vor 50 Jahren segelte er zum Beweis im Papyrusboot über den Atlantik.
Thor Heyerdahl - Umweltaktivist in den Fußstapfen der alten Ägypter
#Atlantik #Kon-Tiki #Papyrusboot #Pazifik #RaII #ThorHeyerdahl #Überquerung
⁢Ƥĥąɳʈȯɱ :fedora: 🎸 🏳️‍🌈 ⁂Steve12L@mamot.fr
2019-07-31

Une nef en roseaux pour traverser la Méditerranée sur les traces des Egyptiens lexpress.fr/actualites/1/actua - Thor Heyerdal l'avait déjà fait. #KonTiki #RaII

Client Info

Server: https://mastodon.social
Version: 2025.07
Repository: https://github.com/cyevgeniy/lmst