Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Providing Custom Deleters For Smart Pointers | Advanced topics
C++ Smart Pointers
course content

Kurssisisältö

C++ Smart Pointers

C++ Smart Pointers

1. Introduction to Smart Pointers
2. Unique Pointers
3. Shared Pointers
4. Weak Pointers
5. Advanced topics

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

cpp

main

copy
1234567891011121314151617181920212223
#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.

cpp

main

copy
1234567891011121314151617181920
#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.

question mark

Why would you use a custom deleter with a smart pointer?

Select the correct answer

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 5. Luku 1
Pahoittelemme, että jotain meni pieleen. Mitä tapahtui?
some-alt