Зміст курсу
Розумні Вказівники C++
Розумні Вказівники C++
Надання Користувацьких Деструкторів для Розумних Вказівників
Користувацькі деструктори надають точний контроль над очищенням ресурсів, забезпечуючи ефективне звільнення пам'яті для різних ресурсів, таких як файлові дескриптори, з'єднання та користувацькі структури даних.
Наприклад, при роботі з файлами за допомогою розумних вказівників, користувацький деструктор може забезпечити, що як динамічна пам'ять звільняється, так і файл правильно закривається, коли вказівник виходить за межі області видимості. Ось як це виглядає:
main
#include <iostream> #include <memory> #include <fstream> void custom_file_deleter(std::ofstream* file) { // Check if file object is accessible and file is open if (file && file->is_open()) file->close(); delete file; // Release memory } int main() { // Creating a smart pointer to a file with a custom deleter std::unique_ptr<std::ofstream, decltype(&custom_file_deleter)> p_file(new std::ofstream("example.txt"), &custom_file_deleter); if (filePtr->is_open()) *filePtr << "Writing to the file using a smart pointer with a custom deleter!\n"; else std::cout << "Failed to open the file!\n"; // Smart pointer automatically closes the file when it goes out of scope }
При створенні унікального вказівника ми передаємо custom_file_deleter
як параметр шаблону. Ключове слово decltype
витягує його тип під час компіляції. Цей користувацький деструктор забезпечує як звільнення пам'яті, так і закриття файлу в одній функції.
Спільні вказівники та користувацькі деструктори
Щоб використовувати користувацький деструктор зі спільним вказівником, передайте його в конструктор спільного вказівника.
main
#include <iostream> #include <memory> // Custom deleter function for a resource void custom_resource_deleter(int* pointer) { std::cout << "Custom deleter called for resource at address: " << pointer << std::endl; delete ptr; } int main() { // Creating a shared pointer with a custom deleter std::shared_ptr<int> p_shared_custom_deleter(new int(42), custom_resource_deleter); // Accessing the shared resource std::cout << "Shared pointer value: " << *p_shared_custom_deleter << std::endl; // The shared pointer automatically manages the resource using the custom deleter }
Створення спільного вказівника на ціле число та вказання користувацького деструктора в конструкторі.
Дякуємо за ваш відгук!