Home > Backend Development > C++ > How to Use Custom Deleters with `std::unique_ptr` Class Members?

How to Use Custom Deleters with `std::unique_ptr` Class Members?

Patricia Arquette
Release: 2024-12-06 07:00:11
Original
921 people have browsed it

How to Use Custom Deleters with `std::unique_ptr` Class Members?

Using Custom Deleters with std::unique_ptr Members

In programming, utilizing a custom deleter with a std::unique_ptr member can provide greater control over the destruction of objects. This article aims to address the question of how to incorporate a custom deleter within a class structure.

Consider a scenario where a class, Foo, contains a member of type std::unique_ptr. Bar is a third-party class that offers both a create() and destroy() function. When working with std::unique_ptr in a stand-alone function, the following syntax can be employed:

void foo() {
    std::unique_ptr<Bar, void(*)(Bar*)> bar(create(), [](Bar* b){ destroy(b); });
}
Copy after login

This approach allows for the specification of a custom deleter using a lambda expression. The question arises: is there a way to replicate this behavior when std::unique_ptr is utilized as a member of a class?

Solution: Custom Deleter for Class Member

Assuming that create and destroy are free functions, the following solution can be implemented:

class Foo {

    std::unique_ptr<Bar, void(*)(Bar*)> ptr_;

    // ...

public:

    Foo() : ptr_(create(), destroy) { /* ... */ }

    // ...
};
Copy after login

In this scenario, the custom deleter is provided directly within the class definition. The destroy function is utilized as the deleter, negating the need for a lambda expression. This approach ensures that the Bar object is properly destroyed when the Foo object goes out of scope.

The above is the detailed content of How to Use Custom Deleters with `std::unique_ptr` Class Members?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template