Home >Backend Development >C++ >Can std::shared_ptr be used for reliable cleanup at shutdown?

Can std::shared_ptr be used for reliable cleanup at shutdown?

DDD
DDDOriginal
2024-11-03 08:03:30403browse

Can std::shared_ptr be used for reliable cleanup at shutdown?

std::shared_ptr: An Unexpected Functionality

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, where it's employed for arbitrary cleanup at shutdown. While seemingly counterintuitive, this technique raises fundamental questions about the behavior and reliability of 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 is copied to a std::shared_ptr, the deleter function remains intact. The stored deleter is responsible for calling the Test destructor in our example.

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:

  • Type erasure: The decoupling of the shared_ptr's internal type can lead to unexpected behavior if the implementation changes in the future.
  • Deleter function: The implementation of std::shared_ptr is not obligated to implement a deleter function for void*.

Therefore, the use of std::shared_ptr for arbitrary cleanup may be a risky practice and is not recommended for reliable code.

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!

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