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: |

Telegram today rolling out an update which brings with it several new features.The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations.

How Does Bitcoin Mining Work?

Bitcoin mining is the process of adding new transactions to the Bitcoin blockchain. It’s a tough job. People who choose to mine Bitcoin use a process called proof of work, deploying computers in a race to solve mathematical puzzles that verify transactions.To entice miners to keep racing to solve the puzzles and support the overall system, the Bitcoin code rewards miners with new Bitcoins. “This is how new coins are created” and new transactions are added to the blockchain, says Okoro.

telegram from ms


Telegram C++ geek
FROM USA