Home >Backend Development >C++ >How Can I Use Custom Deleters with std::unique_ptr Members in a C Class?

How Can I Use Custom Deleters with std::unique_ptr Members in a C Class?

Susan Sarandon
Susan SarandonOriginal
2024-12-08 12:16:11726browse

How Can I Use Custom Deleters with std::unique_ptr Members in a C   Class?

Custom Deleters with std::unique_ptr Members

In C , the std::unique_ptr class offers a convenient way to manage ownership of pointer-based objects. However, if you're working with third-party objects that require a customized deletion process, you may face challenges when using std::unique_ptr as a member of a class.

Consider the following scenario: you have a class with a std::unique_ptr member. The Bar class is from a third-party library and defines its own create() and destroy() functions for object instantiation and destruction.

To utilize std::unique_ptr with such a scenario in a standalone function, you can use a custom deleter:

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

But how can you achieve this when the std::unique_ptr is a member of a class?

Custom Deleters in Class Members

Assuming that create and destroy are free functions with the following signatures:

Bar* create();
void destroy(Bar*);

You can define your Foo class as follows:

class Foo {

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

    // ...

public:

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

    // ...
};

In this implementation, you're directly providing the destroy function as the deleter for the std::unique_ptr. By using a free function as a deleter, you avoid the need for lambdas or custom deleter classes.

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

Statement:
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