Home > Backend Development > C++ > How Can I Use a Custom Deleter with a `std::unique_ptr` Member Variable?

How Can I Use a Custom Deleter with a `std::unique_ptr` Member Variable?

Barbara Streisand
Release: 2024-12-18 12:22:10
Original
522 people have browsed it

How Can I Use a Custom Deleter with a `std::unique_ptr` Member Variable?

Using a Custom Deleter with a std::unique_ptr Member

When working with a std::unique_ptr member in a class, there are instances where a custom deleter may be required. This is particularly relevant when the member object requires specific cleanup or destruction procedures.

Consider a scenario where your class has a member std::unique_ptr, and Bar is a third-party class with its own create() and destroy() functions. To handle the unique ownership of this member, a custom deleter can be implemented.

In a standalone function, you could utilize a std::unique_ptr with a custom deleter like so:

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

Now, let's adapt this approach to a situation where std::unique_ptr is used as a member in a class called Foo:

class Foo {
private:
    std::unique_ptr<Bar, void(*)(Bar*)> bar_;
    ...
public:
    Foo() : bar_(create(), destroy) { /* ... */ }
    // ...
};
Copy after login

Notice that no lambda or custom deleter is necessary in this implementation because destroy itself serves as the deleter. This allows for a clean and concise way to manage the unique ownership of the Bar member while utilizing its custom destruction procedure.

The above is the detailed content of How Can I Use a Custom Deleter with a `std::unique_ptr` Member Variable?. 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