Telegram Group & Telegram Channel
🧵 RAII — главный секрет устойчивого к утечкам C++ кода

Привет! Сегодня хочу напомнить о технике, без которой невозможно писать безопасный и устойчивый C++ код — это RAII (Resource Acquisition Is Initialization).

RAII — это идиома, в которой захват ресурса (файл, сокет, память, мьютекс) происходит в конструкторе объекта, а освобождение — в деструкторе. Благодаря этому ресурсы освобождаются автоматически, даже при исключениях.

Пример:


#include <fstream>

void saveData(const std::string& filename) {
std::ofstream file(filename); // открытие файла
if (!file.is_open())
throw std::runtime_error("Cannot open file");

file << "some data"; // файл закроется автоматически
}


RAII делает твой код:
Безопасным к утечкам
Устойчивым к исключениям
Лёгким для чтения и сопровождения

💡 Совет: всегда оборачивай "ручные" ресурсы в обёртки — std::unique_ptr, std::lock_guard, std::ofstream, std::thread и т.д.


➡️ @cpp_geek



tg-me.com/cpp_geek/295
Create:
Last Update:

🧵 RAII — главный секрет устойчивого к утечкам C++ кода

Привет! Сегодня хочу напомнить о технике, без которой невозможно писать безопасный и устойчивый C++ код — это RAII (Resource Acquisition Is Initialization).

RAII — это идиома, в которой захват ресурса (файл, сокет, память, мьютекс) происходит в конструкторе объекта, а освобождение — в деструкторе. Благодаря этому ресурсы освобождаются автоматически, даже при исключениях.

Пример:


#include <fstream>

void saveData(const std::string& filename) {
std::ofstream file(filename); // открытие файла
if (!file.is_open())
throw std::runtime_error("Cannot open file");

file << "some data"; // файл закроется автоматически
}


RAII делает твой код:
Безопасным к утечкам
Устойчивым к исключениям
Лёгким для чтения и сопровождения

💡 Совет: всегда оборачивай "ручные" ресурсы в обёртки — std::unique_ptr, std::lock_guard, std::ofstream, std::thread и т.д.


➡️ @cpp_geek

BY C++ geek




Share with your friend now:
tg-me.com/cpp_geek/295

View MORE
Open in Telegram


telegram Telegram | DID YOU KNOW?

Date: |

In many cases, the content resembled that of the marketplaces found on the dark web, a group of hidden websites that are popular among hackers and accessed using specific anonymising software.“We have recently been witnessing a 100 per cent-plus rise in Telegram usage by cybercriminals,” said Tal Samra, cyber threat analyst at Cyberint.The rise in nefarious activity comes as users flocked to the encrypted chat app earlier this year after changes to the privacy policy of Facebook-owned rival WhatsApp prompted many to seek out alternatives.

The Singapore stock market has alternated between positive and negative finishes through the last five trading days since the end of the two-day winning streak in which it had added more than a dozen points or 0.4 percent. The Straits Times Index now sits just above the 3,060-point plateau and it's likely to see a narrow trading range on Monday.

telegram from id


Telegram C++ geek
FROM USA