Home > Backend Development > C++ > How does std::shared_ptr work for arbitrary cleanup at shutdown?

How does std::shared_ptr work for arbitrary cleanup at shutdown?

Susan Sarandon
Release: 2024-10-30 14:34:11
Original
455 people have browsed it

How does std::shared_ptr<void> work for arbitrary cleanup at shutdown? 
work for arbitrary cleanup at shutdown? " />

Why std::shared_ptr Works

Despite expectations, std::shared_ptr can be used to perform arbitrary cleanup at shutdown, even when using std::shared_ptr. This behavior stems from type erasure, an integral aspect of std::shared_ptr implementation.

Type Erasure

When a shared_ptr is created, it encapsulates the owned pointer along with a deleter function. This function typically defaults to calling delete but can be configured differently through the constructor. Upon destruction of the shared_ptr, the stored deleter is invoked, triggering the object's cleanup.

To understand type erasure, consider the following simplified example using std::function:

<code class="cpp">template <typename T>
void delete_deleter(void *p) {
    delete static_cast<T *>(p);
}

template <typename T>
class my_unique_ptr {
public:
    my_unique_ptr(T *p, void(*deleter)(void *p) = &delete_deleter<T>) 
        : p(p), deleter(deleter) 
    {}

    ~my_unique_ptr() {
        deleter(p);
    }

private:
    T *p;
    void(*deleter)(void *);
};

int main() {
    my_unique_ptr<void> p(new double);
}</code>
Copy after login

Here, my_unique_ptr can be constructed from a pointer of any type. The deleter stores the type-specific deletion function, ensuring that the correct destructor is called during cleanup.

std::shared_ptr and Type Erasure

Shared pointers also employ type erasure. When copying or default constructing a shared_ptr from another, the deleter information is preserved. This means that a shared_ptr constructed from a shared_ptr maintains the necessary knowledge to call the appropriate destructor, even when cast to shared_ptr.

According to the C standard, this behavior is guaranteed. Implementations cannot change the internals of std::shared_ptr in a way that would break this functionality. Therefore, using std::shared_ptr for arbitrary cleanup is a legitimate and reliable technique.

The above is the detailed content of How does std::shared_ptr work for arbitrary cleanup at shutdown?. 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