Home >Backend Development >C++ >How does std::shared_ptr
work for arbitrary cleanup at shutdown? " />
Despite expectations, std::shared_ptr can be used to perform arbitrary cleanup at shutdown, even when using std::shared_ptr
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>
Here, my_unique_ptr
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
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
The above is the detailed content of How does std::shared_ptr