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

How to Use Custom Deleters with `std::unique_ptr` Member Variables? ```

Barbara Streisand
Release: 2024-12-15 17:07:11
Original
749 people have browsed it

How to Use Custom Deleters with `std::unique_ptr` Member Variables?
```

Using Custom Deleters with std::unique_ptr Member Variables

When working with third-party classes that require a specific deletion mechanism, you may encounter scenarios where you need to use a custom deleter with std::unique_ptr member variables. This article provides a solution for achieving this.

Problem

Imagine you have a class Foo with a member variable of type std::unique_ptr. In this scenario, the third-party class Bar has a dedicated create() and destroy() function for object creation and destruction.

Standalone Function Example

In a standalone function, you can use a custom deleter with std::unique_ptr as follows:

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

Using Custom Deleters with Member Variables

To achieve the same functionality when working with member variables, here's the solution:

class Foo {

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

    // ...

public:

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

    // ...
};
Copy after login

In this code:

  • The ptr_ member variable is declared as a unique_ptr of type Bar.
  • The custom deleter is specified as the second template parameter, which is a function pointer with the signature void(*)(Bar*).
  • The class constructor initializes ptr_ using the create() and destroy() functions as the deleter.

This approach allows you to utilize custom deleters for std::unique_ptr member variables conveniently, ensuring proper resource management even for third-party classes.

The above is the detailed content of How to Use Custom Deleters with `std::unique_ptr` Member Variables? ```. 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