Home >Backend Development >C++ >Can std::shared_ptr be used for reliable cleanup at shutdown?
std::shared_ptr
std::shared_ptr, introduced in C 11, provides a way to manage dynamically allocated objects with shared ownership. However, an intriguing use case emerged using std::shared_ptr
The Working Example
Consider the following code snippet:
<code class="cpp">#include <memory> #include <vector> class Test { public: Test() { std::cout << "Test created" << std::endl; } ~Test() { std::cout << "Test destroyed" << std::endl; } }; int main() { std::vector<std::shared_ptr<void>> v; { v.push_back(std::shared_ptr<Test>(new Test())); } return 0; }</code>
Surprisingly, this code outputs:
Test created Test destroyed
This suggests that the Test object is destroyed properly even though it's held by a std::shared_ptr
The Underlying Mechanism
std::shared_ptr provides type erasure, separating the type of the managed object from the implementation. Internally, it stores a deleter function that calls the appropriate destructor based on the type of the original object.
When a std::shared_ptr
Standard Compliance and Reliability
While the described behavior currently works, it relies on implementation details and is not guaranteed by the C standard. This is due to two reasons:
Therefore, the use of std::shared_ptr
The above is the detailed content of Can std::shared_ptr be used for reliable cleanup at shutdown?. For more information, please follow other related articles on the PHP Chinese website!