Telegram Group & Telegram Channel
🚀 Сегодня я покажу вам простой, но очень полезный приём в C++: как элегантно управлять временем жизни ресурса с помощью std::unique_ptr и кастомного deleter'а.

📌 Задача: у нас есть не-C++ ресурс, например, FILE* из stdio.h. Мы хотим, чтобы он автоматически закрывался, как только выходит из области видимости.

Вместо ручного вызова fclose, используем std::unique_ptr с кастомным deleter'ом:


#include <memory>
#include <cstdio>

int main() {
// Кастомный deleter для FILE*
auto fileDeleter = [](FILE* f) {
if (f) {
std::puts("Файл закрывается автоматически!");
std::fclose(f);
}
};

// Умный указатель с кастомным deleter'ом
std::unique_ptr<FILE, decltype(fileDeleter)> file(std::fopen("data.txt", "r"), fileDeleter);

if (!file) {
std::perror("Не удалось открыть файл");
return 1;
}

// Файл будет автоматически закрыт в конце блока main()
}


💡 Такой подход безопаснее, чем fopen/fclose, особенно в реальных проектах с множеством return'ов и исключениями. А главное — код остаётся чистым и идиоматичным.

🔥 А вы используете unique_ptr с кастомным deleter’ом в своём коде? Поделитесь, для чего вы его применяли!

➡️ @cpp_geek



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

🚀 Сегодня я покажу вам простой, но очень полезный приём в C++: как элегантно управлять временем жизни ресурса с помощью std::unique_ptr и кастомного deleter'а.

📌 Задача: у нас есть не-C++ ресурс, например, FILE* из stdio.h. Мы хотим, чтобы он автоматически закрывался, как только выходит из области видимости.

Вместо ручного вызова fclose, используем std::unique_ptr с кастомным deleter'ом:


#include <memory>
#include <cstdio>

int main() {
// Кастомный deleter для FILE*
auto fileDeleter = [](FILE* f) {
if (f) {
std::puts("Файл закрывается автоматически!");
std::fclose(f);
}
};

// Умный указатель с кастомным deleter'ом
std::unique_ptr<FILE, decltype(fileDeleter)> file(std::fopen("data.txt", "r"), fileDeleter);

if (!file) {
std::perror("Не удалось открыть файл");
return 1;
}

// Файл будет автоматически закрыт в конце блока main()
}


💡 Такой подход безопаснее, чем fopen/fclose, особенно в реальных проектах с множеством return'ов и исключениями. А главное — код остаётся чистым и идиоматичным.

🔥 А вы используете unique_ptr с кастомным deleter’ом в своём коде? Поделитесь, для чего вы его применяли!

➡️ @cpp_geek

BY C++ geek


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

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

View MORE
Open in Telegram


telegram Telegram | DID YOU KNOW?

Date: |

Launched in 2013, Telegram allows users to broadcast messages to a following via “channels”, or create public and private groups that are simple for others to access. Users can also send and receive large data files, including text and zip files, directly via the app.The platform said it has more than 500m active users, and topped 1bn downloads in August, according to data from SensorTower.

Tata Power whose core business is to generate, transmit and distribute electricity has made no money to investors in the last one decade. That is a big blunder considering it is one of the largest power generation companies in the country. One of the reasons is the company's huge debt levels which stood at ₹43,559 crore at the end of March 2021 compared to the company’s market capitalisation of ₹44,447 crore.

telegram from tr


Telegram C++ geek
FROM USA