Managing Memory Manually

Custom Deleters with std::unique_ptr

What role does the custom deleter in std::unique_ptr play, and when would you need to use it?

Abstract art representing computer programming

std::unique_ptr can be customized with a deleter to control how the managed resource is freed. This feature is useful for handling non-standard resource management scenarios.

What is a Custom Deleter?

A custom deleter is a function or function object that defines how a resource should be released when the std::unique_ptr is destroyed. This is particularly useful when dealing with resources that require specific cleanup actions.

Example

Here’s how you can use a custom deleter with std::unique_ptr:

#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)>
    p(new int(10), CustomDeleter);
}

Explanation

  • Custom Deleter Function: CustomDeleter is defined to handle the deletion of int pointers. It prints a message and then deletes the pointer.
  • Usage with std::unique_ptr: The std::unique_ptr is constructed with the custom deleter and a raw pointer. When the std::unique_ptr goes out of scope, CustomDeleter is called to clean up the resource.

When to Use Custom Deleters

  • Non-Standard Cleanup: When the resource requires special cleanup procedures, such as closing a file handle or releasing a database connection.
  • Integration with C Libraries: When working with C libraries that use their own memory management functions.

Summary

Custom deleters in std::unique_ptr provide flexibility for managing resources that need special handling upon release. By defining a custom deleter, you can ensure that the resource is properly cleaned up according to your specific requirements.

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