Managing Memory Manually

Custom Deleters in Smart Pointers

Can you provide an example of using a custom deleter with a std::unique_ptr and explain its use?

Abstract art representing computer programming

A custom deleter is a powerful feature of std::unique_ptr that allows you to define a specific way to release a resource. This is particularly useful for resources that require custom cleanup.

Example of Custom Deleter

Let’s create an example where we manage a resource that requires a custom cleanup process:

#include <iostream>
#include <memory>

// Custom deleter function
void CustomDeleter(int* p) {
  std::cout << "Custom delete called\n";
  delete p;
}

void CustomDeleterExample() {
  std::unique_ptr<int, decltype(&CustomDeleter)>
    ptr(new int(42), CustomDeleter);
  std::cout << *ptr;  // Output: 42
}

Explanation

Custom Deleter Function: CustomDeleter is a function that prints a message and then deletes the pointer. It takes a raw pointer as an argument.

void CustomDeleter(int* p) {
  std::cout << "Custom delete called\n";
  delete p;
}

Using with std::unique_ptr: The std::unique_ptr is constructed with the raw pointer and the custom deleter. When the unique_ptr goes out of scope, it calls CustomDeleter to release the resource.

std::unique_ptr<int, decltype(&CustomDeleter)>
  ptr(new int(42), CustomDeleter);

Output: When the unique_ptr is destroyed, it outputs "Custom delete called" before deallocating the memory.

When to Use Custom Deleters

Custom deleters are useful in several scenarios:

  • Non-Standard Resource Management: When dealing with resources that do not use new/delete for allocation and deallocation, such as file handles or network connections.
  • Integration with Legacy Code: When interfacing with C libraries that require specific cleanup functions.
  • Additional Logging: For debugging purposes, custom deleters can provide additional information when resources are released.

Conclusion

Custom deleters in std::unique_ptr offer flexibility in managing resources by allowing you to define specific cleanup actions. This can be particularly valuable for non-standard resources or when integrating with existing codebases.

Answers to questions are automatically generated and may not have been reviewed.

3D art showing a progammer setting up a development environment
Part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access

This course includes:

  • 60 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved