Kurssisisältö
C++ Smart Pointers
C++ Smart Pointers
Providing Custom Deleters For Smart Pointers
Custom deleters provide precise control over resource cleanup, ensuring efficient memory deallocation for various resources like file handles, connections, and custom data structures.
For example, when handling files with smart pointers, a custom deleter can ensure that both dynamic memory is freed and the file is properly closed when the pointer goes out of scope. Here’s how:
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 }
When creating the unique pointer, we pass custom_file_deleter
as a template parameter. The decltype
keyword extracts its type at compile time. This custom deleter ensures both memory deallocation and file closure in a single function.
Shared Pointers and Custom Deleters
To use a custom deleter with a shared pointer, pass it to the shared pointer's constructor.
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 }
Creating a shared pointer to an integer and specifying a custom deleter in the constructor.
Kiitos palautteestasi!